Home > OS >  How to make images inside a flexbox of the same height as the shortest image?
How to make images inside a flexbox of the same height as the shortest image?

Time:10-24

In my code, there is a flex box, which has three images inside it. Now, these images are of different sizes. My goal is to equalize the heights of these images, without disturbing the aspect ratio. I can't use object-fit: cover as that would crop the images.

I don't really mind whether the widths of the images are equal or not - I only need the heights to be equal. I was thinking that a solution would be to make the heights of the images equal to the smallest image's height, but then I just ended up scratching my head.

Also, these images will be updated over time, as they are actually portfolio images.

Here's my code:

* {box-sizing: border-box;}
.flex-container {
  display: flex;
  width: 90%;
  justify-content: center;
  margin: auto;
}
.flex-image-container {
  display: flex;
  flex-direction: column;
  margin-right: 10px;
}
.flex-image-container img {
  width: 100%;
}
<div >
  <div >
    <img src="https://dummyimage.com/400x550/000/0011ff.png">
    <button >Some Button</button>
  </div>
  <div >
    <img src="https://dummyimage.com/450x500/000/0011ff.png">
    <button >Some Button</button>
  </div>
  <div  style="margin-right: 0px;">
    <img src="https://dummyimage.com/300x600/000/0011ff.png">
    <button >Some Button</button>
  </div>
</div>
  

CodePudding user response:

There is no CSS way of doing this, you can only adapt all images to the biggest one.

You could try to use some JS for it, for example:

<script type="text/javascript">
    window.onload = () => {
        const imgs = document.querySelectorAll('.flex-container img');
        let min = Infinity;
        for (const img of imgs) {
            const height = img.naturalHeight;
            if (min > height && height > 0) min = height;
        }
        for (const img of imgs) {
            img.style.height = `${min}px`;
        }
    }
</script>

First you calculate the min height of all images, excluding the 0 heights (if the image is not loading), then you apply this height to all images.

  • Related