考虑以下代码:
* {
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;
我希望object-fit: contain
将img
缩小到.box
,由flex容器自动调整大小。它不是我的期望,而是从盒子里溢出来的。我的代码出了什么问题?
答案 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>