【问题标题】:Nested Flexbox stretches Image嵌套的 Flexbox 拉伸图像
【发布时间】:2017-06-17 01:12:54
【问题描述】:

我试图让两个嵌套的 flexboxes 在最里面有一个居中的图像,这将始终适合其容器,同时保持其比例,而不会被拉伸。 图片配上:

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

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

这里的宽度被适当地缩放,但是一旦容器变得太小,高度就会被拉伸。我怎样才能防止这种情况发生?

提前致谢! 雅克

【问题讨论】:

  • 在 Chrome 和 FF 上查看您想要的效果。我没有看到任何拉伸。请澄清。

标签: html css flexbox responsive


【解决方案1】:

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

【讨论】:

  • 这似乎可以防止拉伸,但现在高度溢出并且图像根本没有缩放。
  • @jacquesknie 看到我更新的答案。我的意思是object-fit: contain; 不是封面。
  • 啊,是的,这也行得通!这甚至可能是更好的解决方案。非常感谢!
【解决方案2】:

默认情况下,flexbox 子项的flex-shrink 值为 1,这意味着如果需要,子项将根据需要缩小以适应。

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

【讨论】:

  • 很遗憾这没有任何效果。
【解决方案3】:

浏览器仍然存在图像和 flex 父级问题。

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/

【讨论】:

    猜你喜欢
    • 2019-12-22
    • 2017-02-25
    • 1970-01-01
    • 2016-08-17
    • 2016-05-04
    • 2022-11-01
    • 2018-01-26
    • 2012-07-25
    • 2017-06-06
    相关资源
    最近更新 更多