考虑以下代码:
* {
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>
我希望 object-fit: contain
使 img
收缩到 .box
中,由 flex 容器自动调整大小。出乎我的意料,它从盒子里溢出来了。我的代码有什么问题?
最佳答案
.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>
关于html - 使图像缩放以在适合 flexbox 时保持其纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49347967/