Css aspect ratio to have images of same height

A trick to prevent page reflow on images loading

The Problem

Sometimes you have a category page with many images, but when the page loads and the images are still loading, each image load reflows the page, making a mess.

If you want all the images to have the same aspect ratio, you can use this trick to apply the same height to the images, even before the images are loaded.

This trick is also useful when you have images of different height, and you want all of them of the same height, you can mask them with overflow: hidden and vertically center them with margin:auto.

The Code

Demo
Demo
Demo and source code

The code of this solution comes from stackoverflow.

The example markup:

<div class="item-image">
  <img src="http://placehold.it/850x600" class="img-responsive">
</div>
<div class="item-content">
  <div class="item-text">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas nec velit nulla. Cras finibus mollis dolor, ac rhoncus diam. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Proin gravida iaculis orci eget malesuada. Morbi pulvinar, purus sit amet porta laoreet, quam orci fermentum leo, in interdum ligula elit id magna. Nam justo massa, ultrices eget dictum vitae, porttitor eget eros.
  </div>
</div>

The css for the aspect ratio and the item contents:

/* item styles */
.item-image {
  position: relative;
  overflow: hidden;
  padding-bottom: 50%; /* here the desired aspect ratio */
}
.item-image img {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}
.item-content {
  padding: 15px;
  background: #72cffa;
}
.item-text {
  position: relative;
  overflow: hidden;
  height: 100px;
}

How to calculate the aspect ratio

With padding-bottom: 50% we set the aspect ratio to 1:2; you must replace this value with the desired aspect ratio, to calculate it just follow this steps:

  • Get the desired height and width
  • Calculate height / width * 100
  • Put the value as padding-bottom (you can round it to a decimal point)

For example let's say you want an aspect ratio of 400px width and 240px height, do 240 / 400 * 100, the result is 60, so the padding bottom will be padding-bottom: 60%.