Maintaining A 16:9 Responsive Aspect-Ratio Of An Image Using CSS

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-container img {
      position: absolute;
      top: 0;
      height: 100%;
      object-fit: cover;
   }

As you can see how they are perfectly set at 16:9 ratio in all screen sizes

Desktop
Tablet
Mobile

Reference for checking aspect-ratio

That’s all folks!

Leave a Reply