简体   繁体   English

如何确保弹性物品受其子代的宽度影响?

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

I have the following flex and it's children (img): 我有以下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
}

Sometimes .flex doesn't have width ... other times it has. 有时.flex没有宽度...有时它没有宽度。

How to make sure .flex always have the children's width? 如何确保.flex始终具有孩子的宽度? (In this case that of an image?) (在这种情况下是图像吗?)

What you're looking for is to apply width: fit-content to the flex element. 您正在寻找的是将width: fit-content应用于flex元素。

Without this, .flex in the following example will stretch to the edge of the container. .flex ,下面的示例中的.flex将延伸到容器的边缘。
With this, .flex only stretches as wide as the content contained within (in this case, the image): 这样, .flex只能拉伸其中包含的内容的宽度(在本例中为图像):

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

Hope this helps! 希望这可以帮助! :) :)

As fit-content , which one set as the parents width , lack reasonable browser support, use inline-flex . 作为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> 


Note, because of inconsistency between the browsers, an img as a flex item might render differently and a wrapper normally fixes that. 请注意,由于浏览器之间的不一致,作为弹性项目的img可能会呈现不同的外观,而包装程序通常可以解决该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM