Images in row having equal height
Sometimes, you may need to display logos in the footer. However, these logos might come in various sizes and aspect ratios. Despite the differences, you would like to ensure that the row of images appears with the same height. How can you achieve this using CSS?
Enter Flexbox 💪
So, how does this work? There is one requirement: you need either the aspect ratio as a value or the width and height properties to calculate the aspect ratio.
To achieve the desired equal height for images with different aspect ratios using Flexbox, you can follow these steps:
- Calculate the aspect ratio for each image by dividing the width by the height.
- For example, if the image has a width of 1440 pixels and a height of 900 pixels, the aspect ratio would be 1440 / 900 = 1.6.
- For a 'portrait' example with a width of 400 pixels and a height of 1200 pixels, the aspect ratio would be 400 / 1200 = 0.333.
- For each image element or wrapper element, set the
flex
attribute with the corresponding aspect ratio. This will ensure that each image's height adjusts according to its aspect ratio, and all images will have the same height within the flex container.
By following these steps, you can make sure that the row of images in the footer will have the same height, even if the individual images have different aspect ratios. This is one of the powerful features of Flexbox in CSS!
<div class="images-in-row">
<img style="flex: calc(width/height)">
<img style="flex: calc(width/height)">
<img style="flex: calc(width/height)">
<img style="flex: calc(width/height)">
</div>
Then the css:
.images-in-row {
display: flex;
gap: 1rem;
}
.images-in-row img {
width: 100%;
height: auto;
object-fit: contain;
}
For a working example check the following codepen:
See the Pen Images in a row with the same height by Wonky (@Wonky) on CodePen.