Stop your web pages from jumping around while images load

If you start reading text before the images are fully loaded, these page jumps can be very distracting. On slower connections, images may take a few seconds to load, creating an unpleasant experience for the user and compromising your first impression.

There is a quick fix to avoiding this issue on your own web pages.

The page jumps occur because the browser does not know the width and height of the images in advance. On a responsive site, the image could be a different height and width depending on the screen size.

We may, however, know the ratio of the image’s height to its width. That will not change for a given image, no matter the screen size.

It’s easy to find an images height to width ratio:

Image height / Image width * 100

For the images in our example, we found the ratio:

217px / 325px * 100 = 66.769230769

With this information, we can place a container around the image that will reserve its place, eliminating page jerk.

To start, place a div element around your image, and give it a class like .image-container. All images with this class must have the same height to width ratio.

1

2

3

4

<div class="image-container">

<img src="image.jpg"/>

</div>

In your CSS, give the .image-container a padding-bottom equal to the height to width ratio, as a percentage. Above, we calculated 66.769230769. Include all of the numbers after the decimal for a precise result.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

.image-container{

position:relative;

padding-bottom:66.78082192%;/* ratio of image height to width */

height:0;

overflow:hidden;

}

.image-containerimg{

position:absolute;

top:0;

left:0;

width:100%;

}

Now, the browser leaves room for the image, eliminating page jerk. The page load is much smoother:

The blank space may look odd as the page loads. We can extend our trick to show a placeholder:

To accomodate different aspect ratios, create multiple image containers and use them where appropriate. Use this technique only where the aspect ratio is certain; images that don’t fit the aspect ratio will look distorted.

A common challenge in responsive design – not just with this technique – is maintaining the right image quality for each screen. Check out the Smashing Magazine article below for ideas on this.