使图像缩放以在适合flexbox时保持其纵横比

时间:2018-03-18 12:38:44

标签: html css flexbox object-fit

考虑以下代码:



* {
  box-sizing: border-box;
  margin: 0;
}
.container {
  display: flex;
  flex-direction: column;
  align-items: stretch;

  width: 400px;
  height: 200px;

  padding: 10px;

  background: red;
}
.box {
  flex: 1;
}
.box img {
  object-fit: contain;
}

<div class="container">
  <h1>lorem ipsum</h1>
  <figure class="box">
    <img src="http://lorempixel.com/400/200/">
  </figure>
</div>
&#13;
&#13;
&#13;

我希望object-fit: containimg缩小到.box,由flex容器自动调整大小。它不是我的期望,而是从盒子里溢出来的。我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

.box也应为display:flex,以便img可以在.box内“增长”。

* {
  box-sizing: border-box;
  margin: 0;
}

.container {
  display: flex;
  flex-direction: column;
  width: 400px;
  height: 200px;
  padding: 10px;
  background: red;
}
.box {
  display: flex;
  flex: 1;
  overflow: hidden;
}
.box img {
  object-fit: contain;
}
<div class="container">
  <h1>lorem ipsum</h1>
  <figure class="box">
<img src="http://placehold.it/400x200">
  </figure>
</div>

https://www.codeply.com/go/k0gsZbwwRq