0

我们在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在其顶部的文本扩展时进行扩展?

4

2 回答 2

2

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>

于 2018-12-01T00:17:10.927 回答
0

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

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

于 2018-11-30T23:23:08.570 回答