Sub topic 14
Reserving space to avoid layout shift
This chapter assumes you know the img element and its attributes, basic CSS sizing, and how breakpoints work in a responsive layout. It also builds on the earlier chapters on aspect ratios and CSS cropping, because the same ratios that decide your crop also decide how much space the browser must hold.
What layout shift is
Layout shift happens when content moves after the user has already seen it. A photo is the usual cause. The browser starts rendering the page before the image file arrives, and it doesn't know how tall the image will be. It lays out the text as if the image took up no height. When the file finishes loading, the image pushes everything below it downward. The reader loses their place, or taps the wrong button.
Browsers measure this as Cumulative Layout Shift (CLS). Each shift is scored by how much of the viewport moved and how far it moved. Google's Core Web Vitals treat a CLS of 0.1 or less as good and above 0.25 as poor. Images without reserved space are among the most common reasons a page fails this check.
Declare width and height on every image
The simplest fix is to put the image's intrinsic pixel dimensions in the width and height attributes.
<img
src="team-800.jpg"
width="800" height="600"
alt="Four colleagues around a whiteboard">Modern browsers read these two numbers and compute an aspect ratio of 4:3 before the file loads. They apply it through a built-in rule equivalent to aspect-ratio: auto 800 / 600. The attributes are not a fixed size in this case. They only supply the ratio. CSS can still make the image fluid, and the reserved height scales with the width.
For that scaling to work, your stylesheet needs a rule like this:
img {
max-width: 100%;
height: auto;
}height: auto tells the browser to derive the height from the width and the ratio. Without it, the height="600" attribute would act as a fixed 600px height. On a narrow screen the image would be squeezed to a width below 800px while keeping 600px of height, which distorts it.
Common mistakes with the attributes
- Writing
width="100%"orwidth="800px". The attributes accept plain integers only. Use CSS for percentages and units. - Using numbers that don't match the file. If the attributes say 800 by 600 and the file is 1200 by 600, the reserved box has the wrong shape. The image then shifts the layout anyway, or gets stretched.
- Setting a CSS
heightwhile leavingwidthfluid. Set one dimension and let the other follow, or set both and useobject-fit. - Forgetting the attributes on images that are inserted by a CMS or script. Check the generated markup, not only your template.
Reserve space with CSS when the box is not the image
Sometimes the box you want differs from the image's own ratio. A hero is cropped to 16:9 whatever the source photo's shape. Here the aspect-ratio property reserves the space, and object-fit decides how the photo fills it.
.hero img {
display: block;
width: 100%;
aspect-ratio: 16 / 9;
object-fit: cover;
object-position: 30% 40%;
background-color: #d9d4cc;
}CSS aspect-ratio on the image overrides the ratio derived from the attributes. The box is 16:9 from the first layout pass, and the photo is cropped into it once loaded. The background-color is a cheap placeholder. It shows a neutral block of the right size while the file downloads, so the reader sees a deliberate empty slot rather than a blank gap.
The same technique works on a wrapper when the image is a background or sits in a card:
.card-media {
aspect-ratio: 4 / 3;
overflow: hidden;
background-color: #e8e4dc;
}
.card-media img {
width: 100%;
height: 100%;
object-fit: cover;
}Here the wrapper holds the space, and the image fills it. Because the image has height: 100% of a box with a definite ratio, the shape never depends on the file.
Art direction changes the ratio
With the picture element, you may serve a wide crop on desktop and a square crop on mobile. The ratios differ, so one pair of width and height values on the img cannot be right for both. Put dimensions on each source as well:
<picture>
<source media="(min-width: 800px)" srcset="hero-wide.jpg" width="1600" height="900">
<img src="hero-square.jpg" width="800" height="800" alt="A baker lifting a loaf from a stone oven">
</picture>The browser picks the matching source, then uses that source's dimensions to compute the ratio. At 800px and wider the reserved box is 16:9. Below that, it uses the img values and reserves a square. If you leave the dimensions off the source, the browser reserves a space with the img ratio, a square. A wide image then replaces it, and the page shifts on every desktop visit.
Keep the img element's own dimensions matched to its fallback file, because the img is what the browser renders in the end.
Responsive images with srcset
When you offer several widths of the same crop with srcset and sizes, all the files share one ratio. You declare the dimensions of one of them, and the ratio carries over to the others.
<img
src="team-800.jpg"
srcset="team-400.jpg 400w, team-800.jpg 800w, team-1600.jpg 1600w"
sizes="(min-width: 960px) 50vw, 100vw"
width="800" height="600"
alt="Four colleagues around a whiteboard">All three files must be 4:3. If the 1600px file were cropped differently, the box would be reserved at 4:3 and the browser would show a distorted or mismatched image when it picks the larger one. Export every width from the same crop.
Lazy loading and the space it needs
Adding loading="lazy" delays images below the fold until the reader scrolls near them. This saves bandwidth, but it makes dimensions more important. A lazy image has not been fetched when layout happens, so the browser has nothing but your attributes to go on. Every lazy image without reserved space shifts the page as the reader scrolls.
Don't lazy-load the main image at the top of the page. It is likely to be the Largest Contentful Paint element, and delaying it makes the page feel slower. Load it eagerly, which is the default.
Finding shifts in your own pages
- Open the page in Chrome DevTools and go to the Performance panel. Record a load with network throttling on, for example Fast 4G. Shifts appear in the Experience track as red "Layout Shift" markers.
- Click a marker. The summary lists the elements that moved. An image with no dimensions often appears as the source or as the element that pushed others down.
- Run Lighthouse. The "Image elements do not have explicit width and height" audit lists every offender by file name.
- Test with the cache disabled. A cached image loads instantly and hides the problem you are looking for.
Summary of the decision
| Situation | What reserves the space |
|---|---|
| Image shown at its natural shape | `width` and `height` attributes with `height: auto` in CSS |
| Image cropped into a fixed ratio | CSS `aspect-ratio` with `object-fit: cover` |
| Art direction with `picture` | `width` and `height` on each `source` and on the `img` |
| Several widths in `srcset` | One shared ratio, dimensions of one file on the `img` |
| Image in a card or wrapper | `aspect-ratio` on the wrapper, image at 100% of it |
Exercise
A page uses a picture element with a wide source for viewports of 800px and above and a square img fallback. The img has width="800" height="800", and the source has no dimensions. Desktop visitors see the content jump when the image loads. Why does this happen, and how do you fix it?
Show answer
Before the file loads, the browser reserves space using the img's 800 by 800 ratio, which is square. On desktop the wide source is chosen, and the image that arrives is 16:9, so the box changes height and the content below moves. The fix is to add width and height to the source that match the wide file, for example width="1600" height="900". The browser then reserves a 16:9 box when that source matches.
Exercise
An image has width="1200" height="800" and your stylesheet contains only img { max-width: 100%; }. On a 400px-wide phone the photo looks squashed. What is missing and why?
Show answer
The stylesheet lacks height: auto. Without it, the height="800" attribute applies as a fixed 800px height, while max-width shrinks the width to 400px. The 3:2 shape is lost. Adding height: auto makes the browser compute the height from the width and the ratio, so the image would be 400px by about 267px.