Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fit images with varying sizes in a flex row?

Tags:

css

flexbox

My understanding of flex is that this;

<div class="flex-container">
   <img src="image-1">
   <img src="image-2">
   ...
   <img src ="image-n">
</div>

<style>
   .flex-container {
     display: flex;
     justify-content: space-between;
   }
   .flex-container img {
     flex-shrink: 1;
   }
</style>

with random number of random sized images should produce a block of images of width 100% of its parent with the images reduced in size proportionally to fit. I don't want to wrap the items.

The result of the above is either an overflow of the container or distorted images with varying results depending on setting max- or min-height styles on parent or children.

My understanding is obviously wrong. But why?

I have added the snippet below, in Chrome the images fit the box but are distorted, in Firefox they spill out of the box.

like image 426
Chris Pink Avatar asked Jan 28 '26 11:01

Chris Pink


1 Answers

Setting the images to display: block is not sufficient. They need to be enclosed.

Thanks to Adriano for the comment suggestion.

<div class="flex-container">
   <div>
     <img src="image-1">
   </div>
   <div>
   <img src="image-2">
   </div>
   ...
   <div>
    <img src ="image-n">
   </div> 
</div>

<style>
   .flex-container {
     display: flex;
     justify-content: space-between;
   }
   .flex-container div {
     flex-shrink: 1;
   }
   .flex-container div img {
     width: 100%;
     height: auto;
   }
</style>
like image 154
Chris Pink Avatar answered Jan 31 '26 02:01

Chris Pink