首页 > 解决方案 > 使用其他元素调整 div 中的图像大小

问题描述

我有一个带有图像和可变数量的文本的 div,这些文本可能组成 0、1 或多行。如何让图像调整大小,以使两个元素的组合不会超过父 div 的高度?

在下面的示例中,图像占据了 div 的全高 (30vh),文本 div 在下方。我希望图像占用尽可能多的空间,因此如果有 0 行文本,它将占用整个 div,并且仅调整大小以使文本适合父 div。

#test {
  height: 30vh;
  width: 50%;
}

img {
  max-height: 100%;
  object-fit: cover;
}
<div id="test">
  <img src="..."><br />
  <div>Variable amount of text</div>
</div>

我正在使用 Bootstrap 4,如果它具有使这更容易的任何功能。

标签: htmlcssbootstrap-4

解决方案


容器(.test应该是一个 flexbox 列)。而不是 img 使用 div 与图像作为背景和flex: 1.

.test {
  display: flex;
  flex-direction: column;
  height: 30vh;
  width: 50%;
}

.img {
  flex: 1;
  background: url(https://picsum.photos/id/464/200/300) no-repeat;
  background-size: contain;
}
<div class="test">
  <div class="img"></div>
  <div>Variable amount of text</div>
</div>

<div class="test">
  <div class="img"></div>
  <div>Variable amount of text Variable amount of text Variable amount of text Variable amount of text</div>
</div>


推荐阅读