代码之家  ›  专栏  ›  技术社区  ›  Madamadam

文本右对齐到百分比大小的图像

  •  1
  • Madamadam  · 技术社区  · 7 年前

    我想实现这种布局:左侧是一幅图像,右侧是一段文字(多个段落),始终使用可用的水平空间。图像和文本之间的距离应始终为1em。我希望图像使用可用水平空间的百分比(20%)作为宽度,但它决不能小于140px(最小宽度:140px)。此外,即使文本的高度比图像长,也应保持其垂直线,并且不应在图像下方浮动。

    在下面的代码中使用两列是行不通的,因为定义最小图像宽度会破坏布局。也许可以通过使用flexbox来完成所需的布局?

    注意:我不选择使用媒体查询。

    *********  Lorem ipsum
    * Image *  On the right, the text uses the
    * Image *  available space.
    * Image *  The text is made of multiple para-
    * Image *  graphs. Important is, that even 
    *********  if the text is longer in height
               than the image, it should keep its
               vertical line and should not float
               under the image.
    

    .left {
      float: left;
      width: 25%;
    }
    
    .right {
      box-sizing: border-box;
      float: left;
      width: 75%;
      padding-left: 1em;
    }
    
    img {
      max-width: 100%;
      height: auto;
      min-width: 140px;
    }
    
    .right p:first-of-type {
      margin-top: 0;
      padding-top: 0;
    }
    <div class="group">
      <div class="left">
        <img src="http://lorempixel.com/640/480/" alt="" />
      </div>
      <div class="right">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima corporis voluptates
          <p>
            hfbvhjadfbv jsdfbjsdbfbjkvsvd hjfdbg sdbfhj dfhjb dfhjsbjhdv hdf
          </p>repellat ullam labore qui voluptatum error nesciunt ratione dolorem fugiat veritatis ipsum nobis eius dicta est obcaecati ab animi. Voluptatibus dolores natus sint enim fugiat. Sapiente voluptates enim officiis. Iste repudiandae illo nulla sed
          nam a ratione iure?</p>
      </div>
    
    </div>
    
    <div class="group">
      <div class="left">
        <img src="http://lorempixel.com/640/480/" alt="" />
      </div>
      <div class="right">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima corporis voluptates
          <p>
            hfbvhjadfbv jsdfbjsdbfbjkvsvd hjfdbg sdbfhj dfhjb dfhjsbjhdv hdf
          </p>repellat ullam labore qui voluptatum error nesciunt ratione dolorem fugiat veritatis ipsum nobis eius dicta est obcaecati ab animi. Voluptatibus dolores natus sint enim fugiat. Sapiente voluptates enim officiis. Iste repudiandae illo nulla sed
          nam a ratione iure?</p>
      </div>
    
    </div>
    1 回复  |  直到 7 年前
        1
  •  1
  •   C3roe    7 年前

    如果您不想切换到完全不同的技术,如flexbox,您仍然可以很容易地解决这个问题:

    • 应用 min-width 到列而不是图像
    • 去除 width & float 从第二列开始
    • 添加 overflow:hidden 到第二列(这将阻止文本进入图像下方)

    第二部分很重要,因为它允许第二列内容只占用剩余的可用空间-因此,当由于最小宽度,第一列实际上没有25%的宽度时,当两列的宽度加在一起时,最终不会超过100%。