[英]css3 flex: why img take more width than contains?
為什么.itm
在這種情況下采用寬度400px
而不是160px
? 在其他情況下,div 像孩子一樣采用相同的寬度,但是當 img 更大並且瀏覽器對其進行縮放時 - 我得到了空白空間
如何解決? 我只有一種方式:設置<img height="..." width="..." />
,但我想要更合適的方式,因為我不知道真實的圖像大小。
.box { display: flex; }.box.itm { max-height: 400px; max-width: 400px; background: red; margin-right: 10px; }.box.itm img { max-height: 100%; max-width: 100%; }.box.itm.tst { width: 160px; height: 400px; background: lime; }
<div class="box"> <div class="itm"> <img src="https://picsum.photos/300/750"/> </div> <div class="itm"> <div class="tst">same block with 160x400 sime like img</div> </div> </div>
問題
由於彈性項目沒有定義width
或flex-basis
屬性,作為第一個元素分配的flex
容器空間將占用max-width
大小,第二個項目將占用剩余空間。
解決方案
為彈性項目添加width
和flex-basis
屬性
我不明白為什么會這樣
我通過將最大寬度直接移動到每個圖像來解決這個問題。 就我而言,這解決了問題,但如果容器中不僅有圖片而且還有其他內容,這將無濟於事。
.box { display: flex; }.box.itm { display: flex; background: red; margin-right: 10px; }.box.itm img { max-height: 400px; max-width: 400px; }.box.itm.tst { width: 160px; height: 400px; background: lime; }
<div class="box"> <div class="itm"> <img src="https://picsum.photos/300/750"/> </div> <div class="itm"> <div class="tst">same block with 160x400 sime like img</div> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.