嵌套的 Flexbox 拉伸图像

Nested Flexbox stretches Image

我正在尝试在最里面有两个带有居中图像的嵌套弹性盒,它们将始终适合其容器,同时保持其比例,而不会被拉伸。 图像装有:

img{
    max-height: 100%;
    max-width: 100%;
}

看这里: https://jsfiddle.net/quz4zgb0/2/.

此处宽度缩放正确,但一旦容器太小,高度就会被拉伸。我怎样才能避免这种情况?

提前致谢! 雅克

默认情况下,flexbox children 的 flex-shrink 值为 1,这意味着如果有必要,child 会根据需要收缩以适应需要。

通过将 flex-shrink: 0 添加到 .image-container 元素,您会发现它现在可以正确且统一地缩放。

object-fit: contain;flex-shrink: 0; 应用到 <img> 应该会让你非常接近你想要的。

浏览器在图像和 flex parent 方面仍然存在问题。

Firefox 没有我见过的错误,chrome 有,IE 11 更糟。

虽然还不是所有这些都连贯,但您可以在这里使用绝对定位:

.image-container{
  height: 100%;
  background-color: green;
  display: flex;
  justify-content: center;
  align-items: center;
  position:relative;
}

.image-container img{
  position:absolute;
  top:0;
  bottom:0;
  right:0;
  left:0;
  margin:auto;
  max-height:100%;
  max-width: 100%;
}

.main-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.header,
.footer {
  width: 100%;
  height: 1em;
  background-color: red;
}
.image-container {
  height: 100%;
  background-color: green;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}
.image-container img {
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  margin: auto;
  max-height: 100%;
  max-width: 100%;
}
<div class="main-container">
  <div class="header">header</div>
  <div class="image-container">
    <img src="http://weknownyourdreamz.com/images/circle/circle-08.jpg" />
  </div>
  <div class="footer">footer</div>
</div>

https://jsfiddle.net/quz4zgb0/3/