Preventing CLS with Proper Image Dimensions
One of the most frustrating visual issues on the web is when content shifts around as the page loads. This is known as Cumulative Layout Shift (CLS) — and it directly affects your Lighthouse score and user experience.
CLS is part of Google’s Core Web Vitals, and it measures layout stability. A high CLS means users are seeing elements jump around, which can lead to accidental clicks and a sense of jankiness.
What Causes CLS?
Section titled “What Causes CLS?”A common reason for layout shifts is when images (or ads, embeds, fonts, etc.) load in without predefined dimensions. If the browser doesn’t know the size of the image, it can’t reserve space for it — so once the image loads, the layout jumps.
The Fix: Set width
and height
on Images
Section titled “The Fix: Set width and height on Images”To prevent this, always add width
and height
attributes to your <img>
tags. This lets the browser calculate the correct aspect ratio and reserve the right amount of space before the image is downloaded.
❌ Bad Example
Section titled “❌ Bad Example”<img src="/images/photo.jpg" alt="A nice photo" />
✅ Good Example
Section titled “✅ Good Example”<img src="/images/photo.jpg" alt="A nice photo" width="800" height="600" />
This defines the image’s size and prevents unexpected layout changes.
What About Responsive Images?
Section titled “What About Responsive Images?”Even if you’re using responsive layouts, you should still include width and height attributes. The browser will use those values to calculate the aspect ratio, then scale the image with CSS.
img { width: 100%; height: auto;}
This keeps your design fluid while preserving layout stability.
Using aspect-ratio in CSS
Section titled “Using aspect-ratio in CSS”If you’re using modern CSS, another option is to use the aspect-ratio property:
img { aspect-ratio: 4 / 3; width: 100%; height: auto;}
This is especially useful for background images or media rendered dynamically with JavaScript.
Quick Tips to Improve CLS
Section titled “Quick Tips to Improve CLS”- Use
width
andheight
on all<img>
elements. - Reserve space for embeds (e.g. iframes, videos) using wrappers with fixed aspect ratios.
- Avoid injecting DOM elements above existing content during load.
- Test your site using Lighthouse or Chrome DevTools → Performance tab.
- Keep CLS below 0.1 for a good Core Web Vitals score.
Conclusion
Section titled “Conclusion”Preventing layout shifts is key to improving both user experience and performance metrics. Adding width and height to your images is one of the easiest ways to achieve that.
A stable layout not only looks better — it also feels faster and more professional.