gotchajavascriptMajor
CLS: layout shift caused by images without explicit width/height attributes
Viewed 0 times
CLScumulative layout shiftlayout shiftimage dimensionsaspect-ratiowidth height
Problem
Images without explicit width and height attributes have no reserved space in the layout. When they load, the browser inserts them and pushes surrounding content down, causing a high Cumulative Layout Shift score.
Solution
Always set width and height on <img> elements matching the intrinsic aspect ratio. Pair with CSS height: auto to keep responsiveness.
/ CSS /
img {
max-width: 100%;
height: auto; / preserves aspect ratio from HTML attributes /
}
<!-- HTML -->
<img src="photo.webp" width="800" height="600" alt="..." />
/ CSS /
img {
max-width: 100%;
height: auto; / preserves aspect ratio from HTML attributes /
}
<!-- HTML -->
<img src="photo.webp" width="800" height="600" alt="..." />
Why
Modern browsers use the width/height attributes to calculate the aspect-ratio before the image loads, reserving the correct amount of vertical space. Without them, space is zero until load completes.
Gotchas
- CSS aspect-ratio: 16/9 on the container is an alternative when you cannot know the intrinsic dimensions ahead of time
- Dynamically injected ads and embeds are a common source of CLS that width/height cannot solve — use min-height containers
- Web fonts cause CLS too — use font-display: optional or font-display: swap with size-adjust to prevent shifts
- CLS is cumulative over the page lifetime, not just initial load
Code Snippets
CSS to pair with width/height HTML attributes
/* Preserve aspect ratio while staying responsive */
img {
max-width: 100%;
height: auto;
}
/* Or use aspect-ratio for dynamic content */
.media-container {
aspect-ratio: 16 / 9;
width: 100%;
overflow: hidden;
}Context
When diagnosing high CLS scores in Lighthouse or Chrome DevTools Performance panel
Revisions (0)
No revisions yet.