2

When using an image with max-width in a flex item, the flex item grows more than it should. My expected result is the flex item being as wide as the image. Why this is happening and how can be fixed?

A minimal example of the issue: https://jsfiddle.net/kpy4nra7/

HTML:

<div class='flex'>
   <div>hello</div> 
   <div>hello world</div> 
   <div>
     <img src="https://via.placeholder.com/400x100">
   </div> 
</div>    

CSS:

.flex {
  display: flex;
  flex-direction: column;
  border: 1px solid red;
  align-items: flex-start;
}

.flex div {
  background:pink;
}

.flex img {
  max-width: 50%;
}
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
Arizona
  • 21
  • 1
  • the same as i explained here:https://stackoverflow.com/a/54012225/8620333 .. you use a percentage value so we need a reference. The flex item is first sized and then the image is shrinked (the flex item won't be resized again) – Temani Afif Jan 03 '19 at 13:36
  • 1
    The flex item has the image's initial width as its width, and then the image will take up 50% of that. – Asons Jan 03 '19 at 13:39
  • @TemaniAfif That answer works well as a dupe :) – Asons Jan 03 '19 at 13:40
  • 1
    @LGSon yes, we simply need to add that max-width will also use the width of the containing block as reference and that flex-items are also shrink-to-fit element (when stretch is not used as alignment) – Temani Afif Jan 03 '19 at 13:44

0 Answers0