首页 > 解决方案 > Flexbox,限制可用空间内的图像高度/宽度

问题描述

我有一个固定大小的包装器,包括:

图像出现问题。我希望图像调整大小以适应内容容器的高度和宽度。现在图像在高度上溢出了包装。

这是代码。宽图像表现正确,调整大小以适应,但长长颈鹿不是。在下面的小提琴溢出设置为滚动到调试。最终目标是没有溢出。 https://jsfiddle.net/sghp68r0/

一个不太灵活的解决方案就是给 imageFit 类一个高度,比如

img {
  max-width: 100%;
  max-height: 100%;
}
.imageFit {
  object-fit: contain;
  height: 150px;
}

但这我宁愿避免对高度进行硬编码。

我的目标是它看起来像这样(没有溢出):结果

标签: htmlcssflexbox

解决方案


如果我是对的,你想要这个。请务必让我知道。

拖动小提琴中的高度,您会看到图像正在调整高度。

这是我的小提琴链接:-

https://jsfiddle.net/exa3y7w9/

<div class="wrapper">
  <div class="header">
    Sized to content <br />
    Sized to content <br />
  </div>
  <div class="content">
    <div class="imageWrapper">
      <img src="https://cdn.pixabay.com/photo/2017/10/10/22/24/wide-format-2839089_960_720.jpg">
    </div>
    <div> 2 images and some text that fills remaining space </div>
    <div class="imageWrapper">
      <img src="http://clipart-library.com/data_images/258951.jpg">
    </div>
  </div>
  <div class="footer">
    There is some text in fixed size container
  </div>
</div>

推荐阅读