html - 使用其他元素调整 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,如果它具有使这更容易的任何功能。
解决方案
容器(.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>
推荐阅读
- sql - Django:如何只更新数据库中的一条记录?
- coordinates - 在xarray中交换纬度和经度位置
- regex - 解析 Rest 查询输出
- html - CSS:page-break-inside:避免在表格行中不起作用
- python - 使用 Redis 进行 Django 缓存
- sql - PostgreSQL:如何阅读并行解释分析(行与单线程不匹配)
- regex - 如何使用 cypress 和 RegEx 获取当前 URL 的一部分
- sql - 有没有办法在 CASE - WHEN 在 oracle 中添加语句
- javascript - jQuery:使用多个下拉菜单时获取(1)选定的值
- llvm - 如何在 LLVM IR 中创建字符串