[英]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可以在.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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.