1

If I have a flexbox with a max-width: 500px, and inside I have 3 img elements, they extend beyond the max-width of the flexbox.

However, if I wrap all of those img elements in a div, they remain contained within the max-width of the flexbox.

I thought it might be due to the display property, but changing the img element to display: block also doesn't keep it contained.

Overflow of flexbox:

.flex-box {
  display: flex;
  justify-content: center;
  align-items: center;
  max-width: 500px;
  margin: 0 auto;
}

img {
  width: 100%;
  max-width: 100%;
  
}
<div class="flex-box">
  <img src="https://images.pexels.com/photos/1586154/pexels-photo-1586154.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" alt="">
  <img src="https://images.pexels.com/photos/1586154/pexels-photo-1586154.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" alt="">
  <img src="https://images.pexels.com/photos/1586154/pexels-photo-1586154.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" alt="">
</div>

Contained within flexbox:

.flex-box {
  display: flex;
  justify-content: center;
  align-items: center;
  max-width: 500px;
  margin: 0 auto;
}

img {
  width: 100%;
  max-width: 100%;
  
}
<div class="flex-box">
  <div>
    <img src="https://images.pexels.com/photos/1586154/pexels-photo-1586154.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" alt="">
  </div>
  <div>
    <img src="https://images.pexels.com/photos/1586154/pexels-photo-1586154.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" alt="">
  </div>
  <div>
    <img src="https://images.pexels.com/photos/1586154/pexels-photo-1586154.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260" alt="">
  </div>
</div>
  • 2
    the trick is with the percentage used in width/max-width .. in the first case it's relative to the container (width:700px) and in the second case it's relative to the div which is a flex item and its size depend on the content (read the duplicate to understand this part) – Temani Afif Aug 25 '20 at 23:23
  • 1
    @TemaniAfif It seems too obvious once you point that out...is there any way to keep all images contained inside of the flexbox without having to wrap them in all individual divs? – Phillip Choi Aug 25 '20 at 23:36
  • 2
    yes, min-width:0 to the image – Temani Afif Aug 25 '20 at 23:37

0 Answers0