首页 > 解决方案 > 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;
}

https://codepen.io/jeffrey-robert/pen/yLbNVZp

标签: htmlcssimagelayoutflexbox

解决方案


如果您使用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>


推荐阅读