I have the following flex and it's children (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.
How to make sure .flex always have the children's width? (In this case that of an image?)
What you're looking for is to apply width: fit-content
to the flex element.
Without this, .flex
in the following example will stretch to the edge of the container.
With this, .flex
only stretches as wide as the content contained within (in this case, the image):
.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
.
.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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.