簡體   English   中英

如何確保彈性物品受其子代的寬度影響?

[英]How to make sure a flex item is affected by its children's width?

我有以下flex,它是孩子(img):

在此處輸入圖片說明

<div class="flex">
  <img>
</div>

.flex {
  position: relative
  -webkit-box-pack: center!important
  display: flex!important
  box-sizing: inherit
}

img {
  max-height: 124px
  height: 100%
  vertical-align: middle
  box-sizing: inherit
}

有時.flex沒有寬度...有時它沒有寬度。

如何確保.flex始終具有孩子的寬度? (在這種情況下是圖像嗎?)

您正在尋找的是將width: fit-content應用於flex元素。

.flex ,下面的示例中的.flex將延伸到容器的邊緣。
這樣, .flex只能拉伸其中包含的內容的寬度(在本例中為圖像):

 .flex { display: flex; border: 1px solid red; width: fit-content; } 
 <div class="flex"> <img src="http://placehold.it/100"> </div> 

希望這可以幫助! :)

作為fit-content ,其中一個設置為父母width ,缺乏合理的瀏覽器支持,請使用inline-flex

 .flex { display: inline-flex; box-sizing: inherit; border: 1px dotted blue; align-items: center; /* vert. align img */ } .flex img { display: block; max-height: 124px; height: 100%; box-sizing: inherit; } 
 <div class="flex"> <img src="http://placehold.it/500x350/"> </div> <div class="flex"> <img src="http://placehold.it/500x50/"> </div> 


請注意,由於瀏覽器之間的不一致,作為彈性項目的img可能會呈現不同的外觀,而包裝程序通常可以解決該問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM