TLDR How to prevent layout shifts from image loading in 2021

November 2, 2020

Preventing layout shifts when loading responsive images used to be quite hacky.

The most common solution to this problem used to be the "padding hack".

Don't get me wrong, I don't think it's a bad solution at all, as it solves the problem. But since all modern browsers support the needed features nowadays, there is a simpler solution.

The Solution

Suppose you have an image that is 1920x1080. You want to make it responsive and prevent layout shifts.


Set the height and width of the image in HTML, this does not have to be the actual size of the image It can also be the aspect ratio.

<img src="landscape.jpeg" height="16" width="9" />


Add this in the CSS for the image.

img {
  display: block;
  width: 100%;
  height: auto;

You can see an example of this working here.

Also, check out this video if you want an in-depth explanation of why this works.