首页 > 解决方案 > 图像溢出固定高度的 flex 容器

问题描述

我正在使用固定高度的 flex 容器来进行布局。在容器中,共有三个组件:页眉、内容、页脚。我想强制内容使用剩余的高度(即内容高度=固定高度减去页眉和页脚)。在我的内容中,它将包括一张图片和一些文字。

但是,即使提供 max-height: 100% 来限制高度,图像总是会溢出固定高度的弹性容器,但我想将页眉、内容和页脚放入固定的弹性容器中。

有谁知道如何修理它?

代码:https ://codepen.io/mrchung402/pen/wvGPJxz

<div class="container">
  <div class="header">
     header
  </div>
  <div class="content"> 
    <div class="my-img">
      <img src="http://via.placeholder.com/274x295">
    </div>
    <div class="my-text">
      my-text
    </div>
  </div>
  <div class="footer">
    footer
  </div>
</div>

.container {
  border: solid 1px red;
  display: flex;
  max-width: 500px;
  height: 200px;
  flex-direction: column;
}
.header {
  flex: 0 0 auto;
  background: #A7E8D3;
}
.content {
  display: flex;
  flex-direction: column;
}
.footer {
  flex: 0 0 auto;
  background: #D7E8D4;
}
.my-img {
  max-height: 100%;
  height: auto;
  max-width: 100%;
}

img {
  max-height: inherit;
  height: inherit;
}

.my-text {
  background: #C7A8D4;
}

img 溢出弹性项目

标签: htmlcssflexbox

解决方案


而不是造型.my-img,你应该造型.my-img img

.my-img img{
  height: 100%;
  width: 100%;
}

推荐阅读