【问题标题】:How to expand image as text overlay expands?如何在文本覆盖扩展时扩展图像?
【发布时间】:2018-12-01 08:17:10
【问题描述】:

我们在codepen 上有以下代码。我们遇到的问题是我们使用<picture> 属性基于viewport 渲染图像,但无法让图像占用与覆盖在图像上的文本相同的空间量。

codepin 详细信息:

  1. 当前文本有background-color: #eee,因此您可以看到文本占用的区域。
  2. 图像和文字有position: absolute,但可以更改它。
  3. 基于viewport,我们始终希望<source> 标签中的图像只占用文本占用的内容。

目标:

  1. 使图片占据与覆盖在顶部的文本相同的高度和宽度
  2. 使用<picture><source>
  3. 不要在<div class="item__img"> 上使用style: background-image('path/to/image')
  4. 可以裁剪图像以使其适合,但希望在不裁剪的情况下完成。

当前问题:

所需的输出

我们如何让image 扩展为顶部的文本?

【问题讨论】:

    标签: html css image picturefill


    【解决方案1】:

    你可以在你的 img 上使用object-fit 属性:

    .item {
      position: relative;
      width: 33%;
    }
    
    img{
      position:absolute;
      width:100%;
      height:100%;
      object-fit:cover;
    }
    
    .item__text {
      background-color: #eee;
      opacity: 0.5;
      padding:32px;
    }
    <div class="item">
    	<div class="item__img">
    		<picture>
    			<source media="(min-width: 1300px)" srcset="https://placeimg.com/1000/480/nature">
    			<source media="(min-width: 1024px)" srcset="https://placeimg.com/960/480/nature">
    			<img src="https://placeimg.com/640/480/nature" alt="Flowers">
    		</picture>
    	</div>
    	<div class="item__text">
    		<h3>Some title</h3>
    		<p>Efficiently communicate sticky quality vectors after compelling growth strategies. </p>
    	</div>
    </div>

    【讨论】:

      【解决方案2】:

      如果您的图片总是比文本框大,这里有一个解决方案

      .item {
        position: relative;
        max-width: 100%;
      }
        
      .item__img img {
        width: 100% !important;
      }
      	
      .item__text {
        position: absolute;
        background: rgba(238,238,238, 0.5);
        padding: 32px;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        z-index: 5;
        display: flex;
        flex-direction: column;
        justify-content: center;
      }
      <div class="item">
        <div class="item__img">
          <picture>
            <source media="(min-width: 1300px)" srcset="https://placeimg.com/1000/480/nature">
            <source media="(min-width: 1024px)" srcset="https://placeimg.com/960/480/nature">
            <img src="https://placeimg.com/640/480/nature" alt="Flowers" style="width:auto;">
          </picture>
        </div>
        <div class="item__text">
          <div>
            <h3>Some title</h3>
            <p>Efficiently communicate sticky quality vectors after compelling growth strategies. </p>
          </div>
        </div>
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-29
        • 1970-01-01
        • 1970-01-01
        • 2023-01-04
        • 1970-01-01
        • 2015-08-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多