[英]Make an image scales to maintain its aspect ratio while fitting within a flexbox
Considering the following code: 考虑以下代码:
* { 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>
I would expect object-fit: contain
to make the img
shrink into the .box
, automatically sized by the flex container. 我希望
object-fit: contain
使img
缩小为.box
,并由flex容器自动调整大小。 Instead of my expectation, it overflows from the box. 出乎我的意料,它从盒子里溢出了。 What is wrong in my code?
我的代码有什么问题?
The .box
should be display:flex
too so that the img can "grow" within the .box
. .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 https://www.codeply.com/go/k0gsZbwwRq
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.