Fix Layout Shift caused by auto sizing image

Images with auto width and auto height will cause a layout shift. Learn how to fix this

Arjen Karel Core Web Vitals Consultant
Arjen Karel - linkedin
Last update: 2024-08-18

Fix Layout Shift caused by auto sizing image

Did you know there is a very simple and quite common way of killing your Core Web Vitals with just a single CSS statement? It's out there in the wild, I have seen it many times and it will wreak havoc on your CLS.

cls lighthouse auto sizing img

Here it is: the small piece of code that will automatically make all your images shift on the page. It will even cause a layout shift when the width and height of the image have been explicitly set! Also setting the correct aspect-ration CSS value will not fix the problem!

It is a sneaky little Layout Shift problem because it will only happen for first time visits. Since you, as a webmaster, will probably have the image in your browser cache you might not immediately notice the Layout Shift.

<style>
img{
   width:auto;
   height:auto;
   max-width:100%
}
<style>

How did we notice the issue?

It is hard to detect these kind of issues that will mostly appear for new visitors with low bandwidth mobile devices. The answer is RUM Tracking. RUM Tracking tracks the Core Web Vitals for real users and reports is back to you. RUM Tracking is great for finding hidden Core Web Vitals issues!

find auto img cls with coredash

How does it work?

This tiny piece of CSS code is sometimes used for responsive images. When an image is not pre-cached by the browser a browser will have no idea of the intrinsic width and height. With this code it will ignore the set width and height and try to render the page with the intrinsic width and height. Since that is unknown the image will first render at 0x0 pixels and only when the image has been downloaded and decoded will it be re-rendered and take up the correct amount of pixels.

  1. The height: auto; will make sure the image always has the correct height when the image is resized. 
  2. The max-width:100%; will make sure the image is never larger than the visible viewport 
  3. The width:auto; part will generate a layout shift for un-cached images even when you explicitly set the width and height or aspect ratio.

How to fix it?

The fix is easy. Just remove the width:auto. This will force the browser to use the give image width, calculate the auto height based on the height. 

So do yourself a favor, take 15 seconds, inspect a random image on your website (right click, inspect element) and check for width:auto; and height:auto; If you see it, fix it!.

Stop Guessing, Start Measuring

I use Core/Dash to optimize my clients sites. So Should You.

Start your free trial >>

  • Easy set up.
  • Over 5000 happy clients
  • Free trial, No strings attached
Fix Layout Shift caused by auto sizing imageCore Web Vitals Fix Layout Shift caused by auto sizing image