Cover Image
#design #shorts 🔥

Avoid layout flicker during image load

~ 2 MINS READ
8th Dec 2021
Mohammed Omer By Mohammed Omer

Sometimes, when you load a web page you see some flickering in the page layout before the image is downloaded and rendered on the screen. This behavior is not pleasant and makes the page elements move around before images are downloaded.

When we use code like this to render images, the result would be like below:

<img style="width: 100%; height: auto;" src="img/url.png" alt="cover">

profile-flicker-cropped.gif

Why does that happen ?

This happens because the width and the height properties of the img tag (not the CSS properties) are not set, so the browser doesn't know how much height to allocate for the image before it is downloaded and rendered. So we end up with a zero height image during image downloading time.

But if we only used the width and height properties of the img tag, we get the same size regardless of the screen size, which in most cases is not the behavior we want (in HTML5, it is invalid to set height and width attributes as percentages).

Solution

To avoid the above behavior we can use our CSS to define the image width, but we also add the width and height properties of the img tag so that the browser can calculate the correct aspect ratio based on the width and height properties provided.

<img style="width: 100%; height: auto;" src="img/url.png" alt="cover" width="550" height="300">

Now the browser knows the width defined by the CSS width property, which is 100% in our case, and can then calculate how much to allocate for the height based on the ratio between the width and height provided by the HTML width and height properties.

The result would be something like this:

profile-no-flicker-cropped.gif


If you liked this post consider sharing it :

You may also like

stopwatch2 MINS 
cover
By Mohammed Omer | 27th Mar 2022
#laravel #productivity #tooling #shorts 🔥
stopwatch6 MINS 
cover
By Mohammed Omer | 20th Nov 2021
#tailwindcss #design