【问题标题】:Keep image's ratio in a flex container on height resize在高度调整大小时将图像比例保持在 flex 容器中
【发布时间】:2018-01-02 03:32:58
【问题描述】:

我对 flex 容器中的图像有疑问。我希望它在容器/窗口高度减小/缩小时保持比例。

Sample fiddle

html,
body {
  height: 100%;
}

.wrapper {
  display: flex;
  width: 100%;
  height: 60%;
  border: 1px solid red;
}

.image-container {
  display: flex;
  align-items: center;
  max-width: 30%;
  height: 100%;
  background: green;
}

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

.content {
  display: flex;
  justify-content: center;
  align-items: center;
  flex: 1;
  width: 100%;
  height: 100%;
  background: yellow;
}
<div class="wrapper">
  <div class="image-container">
    <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e0/Clouds_over_the_Atlantic_Ocean.jpg/1200px-Clouds_over_the_Atlantic_Ocean.jpg" alt="">
  </div>
  <div class="content">
    <span>Some content</span>
  </div>
</div>

当您尝试这样做时,您会看到只有图像的高度发生变化,但宽度保持不变,并且图像被拉伸了。

当我从图像容器中删除 'display: flex' 时,图像会很好地调整大小。我让它弯曲是因为我想让它居中。

有没有办法保持比例并流畅地调整图像和其他容器的大小?

【问题讨论】:

  • 在这个fiddle 中没有拉伸,宽度和高度都调整了大小。
  • 尝试缩小输出窗口。
  • @pedram,通常在我的应用程序中,我有一个选项,当用户执行特定操作时,此包装容器会降低其高度。这就是为什么我现在谈论窗口大小调整的原因。当您不断降低输出窗口的高度时,您会看到图像的宽度不会改变。
  • 你需要设置height免费,请看这个Fiddle你可以吗?您的图像不是正方形的,您需要将 auto 设置为 height
  • @pedram 不完全是。我想达到当你在块上设置图像容器的显示时可见的效果,就像在这个Fiddle

标签: html css flexbox


【解决方案1】:

只需在 img 标签上添加object-fit: cover;

img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

JSFiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 2018-07-17
    • 2021-06-12
    相关资源
    最近更新 更多