首页 > 解决方案 > 如何在文本覆盖扩展时扩展图像?

问题描述

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

密码详细信息:

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

目标:

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

当前的问题: 当前问题

期望的输出 期望的输出

我们如何image在其顶部的文本扩展时进行扩展?

标签: htmlcssimagepicturefill

解决方案


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

.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>


推荐阅读