繁体   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