Skip to content

Illustration by unDraw

Prevent image layout shifts with padding hack

Prevent layout shifts due to images by preserving their aspect ratio with the padding hack.

This is a minimal, quick, no-fuss guide on how to preserve space for images with an aspect ratio and reduce layout shifts.

Essentially reducing Cumulative Layout Shift and preventing this type of bad user experience:

What an annoying thing right?

So let's get right to it.

The padding hack#

Markup#

<figure>
  <img src="https://cdn.example.com/image.jpg">
</figure>

Styles#

Image parent styles#

figure {
  width: 100%;
  height: 0;
  padding-top: calc(9 / 16 * 100%);
  position: relative;
}

Image styles#

figure > img {
  height: 100%;
  width: 100%;
  object-fit: contain;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
}

The result#

After applying the above code we should get something like this:

Example#

If you would like to have a look at the example shown in the animation above, I've put this Glitch together (live website) that you can play around with.

Use the button on the top right-hand corner to toggle padding hack on/off.

Tip: Open DevTools and simulate a Fast 3G connection. Then scroll down to better observe the layout shifts as the images are being lazy loaded.

(bonus) aspect-ratio property#

The aspect-ratio property is quite a new addition to the CSS spec that adds support for specifying the aspect ratio of an element (img, video, iframe, embed, etc) in a single line of CSS.

img, video {
  aspect-ratio: attr(width) / attr(height);
}

The aspect-ratio property hasn't got a good browser support just yet but it is definitely showing a promising future.

Learn more#