Width/height and CLS
Reduce cumulative layout shift with image dimensions.
What is CLS?
When a late image lands and pushes other content aside, the reader gets jolted. This jump is called cumulative layout shift (CLS). The smaller the CLS, the better.
If you set an image's width and height up front, the browser reserves the slot. The page then does not jump when the image arrives. <img width="800" height="600"> is enough.
How are the sizes written?
The width and height attributes take pixel values, but the px unit is not written. So width="800" is right, width="800px" is not.
These values give the image's intrinsic size. CSS may show it at a different size; the browser still keeps the ratio. Even when the image is scaled down, the page does not jump.
Exercise Write a sized, lazy, async-decoded image
Add a single <img> inside body. It should hold: src (e.g. /images/product.jpg), a non-empty alt, numeric width and height, loading="lazy" and decoding="async".
Show example solution
<body>
<img src="/images/product.jpg"
alt="Product"
width="400"
height="300"
loading="lazy"
decoding="async">
</body>
Test yourself
-
What does setting width and height on an image prevent?
- Image resizing
- Cumulative layout shift (CLS)
- Lazy loading of the image
- Background decoding of the image
Show answer
Cumulative layout shift (CLS) — Correct. width and height tell the browser the slot in advance; no jump.
-
Add width and height to the img
<img src="/images/product.jpg" alt="Product" ____>Show answer
<img src="/images/product.jpg" alt="Product" width="400" height="300"> -
Match each term to its meaning
- width
- Horizontal pixel size
- height
- Vertical pixel size
- CLS
- Layout shift
- ratio
- width/height kept