html - CSS 布局:移动、垂直布局、页眉(固定高度)、页脚(固定高度)。如何用img填充剩余空间,受高度和宽度限制
问题描述
布局:移动、垂直布局、页眉(固定高度)、页脚(固定高度)。如何用img填充剩余空间,受高度和宽度限制
这是我在 iOS 上非常常见的布局。试图了解如何在 CSS 中做到这一点。
这是我正在尝试的:
使用带有 flex-direction 列的 flexbox 设置页眉和页脚的高度(或者可以使用 flex-basis 完成) flex-shrink: 0 用于页眉和页脚,因此它们不会缩小 flex-shrink: 1 在图像容器上使其缩小如果需要,将图像对象适配的最大宽度和最大高度设置为 100%:按比例缩小以保持图像的纵横比(这意味着会有水平条或垂直条)
问题:图像会缩小以适应宽度,但应该缩小得更多以适应可用的垂直空间
HTML
<div class='container'>
<div class='header'>
Header
</div>
<div class='content'>
<div class='image-container'>
<img class="cat" src="https://jngnposwzs-flywheel.netdna-ssl.com/wp-content/uploads/2019/05/Transparent-OrangeWhiteCat-764x1024.png"/>
</div>
</div>
<div class='footer'>
Footer
</div>
</div>
CSS
.container {
background-color: #aaa;
height: 400px;
width: 175px;
display: flex;
flex-direction: column;
border: 2px solid blue;
}
.box {
border: 2px solid black;
display: flex;
justify-content: center;
align-items: center;
}
.box1 {
height: 100px;
flex-shrink: 0;
}
.box2 {
flex-shrink: 1;
}
.cat {
max-width: 100%;
max-height: 100%;
object-fit: scale-down;
border: 2px solid orange;
}
.box3 {
height: 100px;
flex-shrink: 0;
}
解决方案
如果您使用object-fit
,那么诀窍是设置为img
:height:0;min-height:100%;width:100%
并且它应该填充 flex 子框,子框也需要填充 剩余空间。flex-grow:1;
.container {
background-color: #aaa555;
height: 400px;
width: 175px;
display: flex;
flex-direction: column;
border: 2px solid blue;
}
.box {
border: 2px solid black;
display: flex;
justify-content: center;
align-items: center;
}
.box1 {
height: 100px;
flex-shrink: 0;
}
.box2 {
flex:1 1 auto;
}
.cat {
width: 100%;
height:0;
min-height:100%;
object-fit: scale-down;
border: 2px solid orange;
}
.box3 {
height: 100px;
flex-shrink:1;
}
<div class="container">
<div class="box box1">
1
</div>
<div class="box box2">
<img class="cat" src="https://jngnposwzs-flywheel.netdna-ssl.com/wp-content/uploads/2019/05/Transparent-OrangeWhiteCat-764x1024.png"/>
</div>
<div class="box box3">
3
</div>
</div>
推荐阅读
- python - 训练时遇到的BERT模型bug
- shell - 将 unix 文件的行数与多种记录的预告片数进行比较
- javascript - Vue:单击播放音频,再次单击暂停多个曲目
- mysql - SELECT vin 按不同ODO mysql查询排序
- scala - 完成来自演员参考的流?
- javascript - pdfMake - 无法读取 DocPreprocessor.preprocessTable 中未定义的属性“长度”
- python - 使用评估函数对 np.array x 进行排序
- python - 出现后匹配多行的正则表达式
- python - 如何使用 tensorflow 训练和保存多类人工神经网络模型?
- python - 基于行的子集Python数据框