One of the greatest challenges developers face is to maintain an aspect ratio of multiple images with unknown dimensions. In this blog, we will learn just that.
Let’s take an example of these two images with different dimensions. The problem is that we cannot give it a fixed height because the width will change in different dimensions.

So to solve this, let’s wrap these images in a container and add the following styles.
<figure class="img-container">
<img src="..." alt="..." width=".." height="..">
</figure>
<figure class="img-container">
<img src="..." alt="..." width=".." height="..">
</figure>
Styles
.img-container {
position: relative;
width: 100%;
padding-top: 56.25%; /* 16:9 Aspect Ratio */
}
img {
position: absolute;
top: 0;
height: 100%;
object-fit: cover;
}
Please note that if you want to have a square ( 1:1
) aspect ration then, set the padding-top
to `100%` instead of 56.25%
As you can see how they are perfectly set at 16:9 ratio in all screen sizes



Reference for checking aspect-ratio
That’s all folks!
Leave a Reply