【问题标题】:CSS Layout: Mobile, Vertical Layout, Header (fixed height), Footer (fixed height). How to fill remaining space with img, constrained on height & widthCSS 布局:移动、垂直布局、页眉(固定高度)、页脚(固定高度)。如何用img填充剩余空间,受高度和宽度限制
【发布时间】:2021-09-13 19:41:26
【问题描述】:

布局:移动、垂直布局、页眉(固定高度)、页脚(固定高度)。如何用img填充剩余空间,限制高度和宽度

这是我在 iOS 上非常常见的布局。试图了解如何在 CSS 中做到这一点。

这是我正在尝试的:

使用带有 flex-direction 列的 flexbox 设置页眉和页脚的高度(或者可以使用 flex-basis 完成) flex-shrink: 0 表示页眉和页脚,因此它们不会收缩 flex-shrink: 1 在图像容器上,因此如果需要它会缩小 在图像上将最大宽度和最大高度设置为 100% object-fit:按比例缩小以保持图像的纵横比(这意味着会有水平条或垂直条)

问题:图像会缩小以适应宽度,但应该缩小得更多以适应可用的垂直空间

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

【问题讨论】:

    标签: html css image layout flexbox


    【解决方案1】:

    如果你使用object-fit,那么诀窍是设置为img :height:0;min-height:100%;width:100% 并且它应该填充flex子框,子框需要 flex-grow:1; fill the remaing space

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

    【讨论】:

    • 非常感谢,你不知道这难倒了多少人哈哈!我永远猜不到 height:0 min-height:100%
    • @JeffHanna ,这里也需要 flex-grow ,然后 height/min-height 可以工作;)
    猜你喜欢
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-22
    • 2012-11-08
    相关资源
    最近更新 更多