使图像缩放以在适合 flexbox 时保持其纵横比
Make an image scales to maintain its aspect ratio while fitting within a flexbox
考虑以下代码:
* {
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 就可以 "grow" 在 .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>
考虑以下代码:
* {
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 就可以 "grow" 在 .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>