completefrontend
Open lab My progress
THE WEB PERFORMANCE FIELD GUIDE

Fixing layout shifts

Fix layout shifts for real: size images with width, height and aspect-ratio, keep slots for ads, animate with transform, and give skipped content a size.

By the end, you can
  • 01
    Size media before it arrivesUse width and height, or aspect-ratio, so a photo or an embed has its box from the first paint.
  • 02
    Keep room for late contentKeep a slot for ads and notices, choose its size, and keep it when nothing comes.
  • 03
    Move things without shifting the pageAnimate with transform, put late notices over the page, and give skipped content a size.

Fixing Ravi's page, one jump at a time

In lesson 30.2, Asha's screen jumped three times on Ravi's mint tea page. The photo came in with no size. Caveat swapped in over Arial. Then the ad opened in an empty box. Her CLS was 0.2546. Chrome's own CLS, with a hidden jump inside the ad, was 0.3013. Both are "poor".

Now Ravi wants to fix it. He has two questions. Which fix should come first? And can the page get all the way to zero?

He fixes one jump at a time. After each fix, the course loads the page again in Chrome, the same way as in lesson 30.2. Here is Asha's screen before the fixes, and after all of them, at the same four moments:

Real frames of Asha's screen on Ravi's mint tea page, at the same four moments, before and after the fixes. As it was: CLS 0.2546. 60 ms: first paint, no photo yet. 719 ms: photo arrives, score 0.1829. 1333 ms: Caveat swaps in, score 0.0138. 2548 ms: the ad opens, score 0.0580. All four fixes: CLS 0. 47 ms: first paint, space kept. 731 ms: photo arrives, nothing moved. 1331 ms: Caveat swaps in, nothing moved. 2535 ms: the ad opens, nothing moved.As it was: CLS 0.254660 msAs it was: CLS 0.2546, at 60 ms: first paint, no photo yetfirst paintno photo yet719 msAs it was: CLS 0.2546, at 719 ms: photo arrives, score 0.1829photo arrivesscore 0.18291333 msAs it was: CLS 0.2546, at 1333 ms: Caveat swaps in, score 0.0138Caveat swaps inscore 0.01382548 msAs it was: CLS 0.2546, at 2548 ms: the ad opens, score 0.0580the ad opensscore 0.0580All four fixes: CLS 047 msAll four fixes: CLS 0, at 47 ms: first paint, space keptfirst paintspace kept731 msAll four fixes: CLS 0, at 731 ms: photo arrives, nothing movedphoto arrivesnothing moved1331 msAll four fixes: CLS 0, at 1331 ms: Caveat swaps in, nothing movedCaveat swaps innothing moved2535 msAll four fixes: CLS 0, at 2535 ms: the ad opens, nothing movedthe ad opensnothing moved
Real frames from the course's recording in Chrome. Times count from the moment the page started loading. On the fixed page, every box was the right size from the first paint, so nothing on the screen moved.

Look at the first frame in each row. Before the fixes, the steps sit right under the heading. After them, there's an empty space where the photo will go, and another where the ad will go. For a moment, the page looks unfinished. But nothing on it ever moves.

Here is CLS after each fix, from Ravi's script and from Chrome:

CLS after each fixPop out in the code editor (opens in a new tab)JavaScript
// Ravi's page after each fix, recorded in Chrome: [the fix, his page's CLS, Chrome's own CLS].const steps = [  ["as it was", 0.2546, 0.3013],  ["the photo's size", 0.0717, 0.1184],  ["a slot for the ad", 0.0081, 0.0467],  ["a fallback with Caveat's sizes", 0, 0.0467],  ["the ad's photo size", 0, 0],];for (const [fix, page, chrome] of steps) console.log(`${fix}: ${page} on the page, ${chrome} in Chrome`);
  • Line 1 is a comment. Ravi's script reports the page's CLS. Chrome's own CLS also counts jumps inside the ad, which his script can't see.
  • Lines 3 to 7 hold one recorded load each. Each line adds one fix to the ones above it.
  • Line 9 prints one line per load. The first is as it was: 0.2546 on the page, 0.3013 in Chrome. The last is the ad's photo size: 0 on the page, 0 in Chrome.

The first fix did the most. The photo's size alone took Ravi's CLS from 0.2546 to 0.0717. That's under 0.1, so it's "good". But Chrome's own CLS was still 0.1184. It took four fixes to reach 0 in both:

CLS after each fix, as two bars drawn to scale: Ravi's script's CLS, and Chrome's own CLS, which adds the ad's jumps. As it was: 0.2546 on the page, 0.3013 in Chrome. + photo size: 0.0717 on the page, 0.1184 in Chrome. + ad slot: 0.0081 on the page, 0.0467 in Chrome. + fallback font: 0 on the page, 0.0467 in Chrome. + ad's photo size: 0 on the page, 0 in Chrome. A dashed line marks 0.1, the most a good page may have. The numbers sit in a column on the right.Ravi's scriptChrome's own0.1: goodAs it was0.25460.3013+ photo size0.07170.1184+ ad slot0.00810.0467+ fallback font00.0467+ ad's photo size00
Each fix took away one jump. The plain bar is what Ravi's own script sees. The shaded bar is Chrome's own CLS, which also counts the ad's jumps. Left of the dashed line is good: 0.1 or less.

Why it matters: fix the biggest jump first. The scores Chrome wrote in lesson 30.2 tell you which one that is.

Real-life analogySetting a place for every guest

Meera has friends for dinner. Before anyone comes, she sets a place for each one: a plate, a glass, a chair. One friend is late. When he arrives, he sits in his place, and nobody moves. If she had set no place for him, everyone on the bench would shuffle along.

In real life: A place set before the guests come
In JavaScript: A box kept for content before it arrives
In real life: The friend who comes late
In JavaScript: The photo, the font or the ad, after the first paint
In real life: Everyone shuffling along the bench
In JavaScript: A layout shift
In real life: Sitting down in his own place
In JavaScript: Content filling its box, with nothing moving
The main idea

Every fix in this lesson does one of two things. It gives late content its room before it arrives. Or it moves things without changing anyone's place in the layout.

The next four sections take the fixes in turn:

  • Give media its shape: width, height and aspect-ratio.
  • Keep room for late content: ads, fonts and notices.
  • Move things with transform instead of top or height.
  • Give skipped content a size with contain-intrinsic-size.

The course recorded every page in Chrome 157, on Asha's screen: 412 px wide and 823 px tall. As in lesson 30.2, its server held the photo back 700 ms, Caveat 1.3 seconds, and the ad's script 1.9 seconds. Pick a step to see every shift Chrome wrote for it:

Playground: Ravi's page, one fix at a time
What Chrome wroteAs it was
710.3 ms0.1829: #steps, #reviews, #add moved
1328.2 ms0.0138: #reviews, #add, li moved
1913.7 ms0.0580: #reviews, #add moved
2530.1 ms, inside the ad0.2110 there, 0.0467 in Chrome
Ravi's script's CLS0.2546
Chrome's own CLS0.3013
Try it yourself
CLS 0.2546 on the page, 0.3013 in Chrome

Lesson 30.2's page: the photo has no size, the ad has no slot, and Caveat swaps in over Arial. Ravi's script saw 3 layout shifts. The ad's own photo still jumped, and Chrome added 0.0467.

Each button is a real load of Ravi's page in Chrome, with that fix and the ones before it. The server held the photo back 700 ms, Caveat 1.3 seconds and the ad's script 1.9 seconds, as in lesson 30.2.

Give the photo its shape before it arrives

The photo's jump was the biggest: 0.1829. Here is its tag before and after the fix:

The photo's tag, before and afterHTML
<img id="photo" src="mint-tea.jpg" alt="A glass of mint tea"><img id="photo" src="mint-tea.jpg" width="1600" height="1067" alt="A glass of mint tea">
  • Line 1 is the tag from lesson 30.2. It has no width and no height.
  • Line 2 adds the photo file's own size: 1600 by 1067 pixels.

Ravi's CSS still says width: 100% and height: auto. So the photo won't be 1600 px wide. What do the numbers do, then? They tell the browser the photo's shape before its file arrives.

Real-life analogyA frame bought before the print

Ravi orders a big print of the mint tea photo. It will take a week. He knows the photo is 3 by 2, so he buys a 3-by-2 frame today and hangs it on the wall. When the print comes, it slides into the frame. Nothing else on the wall moves.

In real life: The frame's shape, 3 by 2
In JavaScript: The aspect ratio, from width and height
In real life: How much wall there is
In JavaScript: The column's width, from CSS
In real life: Hanging the frame today
In JavaScript: Laying out the box before the file arrives
In real life: The print sliding in
In JavaScript: The photo appearing, with nothing moving

An aspect ratio is a box's shape: its width divided by its height. The HTML standard says that on an img or a video, width and height "map to the aspect-ratio property", in the form auto w / h. The browser reads them with the tag, long before the file. The course read the photo's style in Chrome: aspect-ratio: auto 1600 / 1067.

So the column gives the width, 380 px. The shape gives the height: 380 × 1067 ÷ 1600, or 253.41 px. The box has that height from the very first layout. The course checked where the steps started, once as soon as the HTML was read, and again at the end:

Where the steps startedPop out in the code editor (opens in a new tab)JavaScript
// Where the steps started on each page, in px from the top: [when the HTML was read, at the end].const before = [116, 369.41];const fixed = [369.41, 369.41];console.log(`Before: the steps moved ${(before[1] - before[0]).toFixed(2)} px.`);console.log(`Fixed: the steps moved ${(fixed[1] - fixed[0]).toFixed(2)} px.`);
  • Line 1 says what the numbers are. Both pairs come from the recording.
  • Line 2 is lesson 30.2's page. The steps started at 116 px, under the heading, and ended at 369.41 px.
  • Line 3 is the fixed page. The steps started at 369.41 px and stayed there.
  • Lines 4 and 5 print Before: the steps moved 253.41 px. and Fixed: the steps moved 0.00 px.

Why it matters: two numbers in one tag took away more than two thirds of Asha's CLS.

aspect-ratio for boxes with no attributes

Some boxes have no width and height to give. A map in an iframe is one. On an iframe, the two attributes only set a width and a height, not a shape. For a box like that, write the shape in CSS:

A shape written in CSSCSS
.map { aspect-ratio: 16 / 9; }
img { aspect-ratio: auto 16 / 9; }
  • Line 1 keeps every box with the class map 16 by 9. At 380 px wide, it's 213.75 px tall before the map loads.
  • Line 2 adds auto. That's the form Chrome made from the photo's attributes.

What does auto change? The CSS Sizing spec says it lets a replaced element keep its own aspect ratio. A replaced element is one whose content comes from outside the page, like an image or a video. So once the file arrives, its real shape wins. If the numbers in the tag are wrong, the box still jumps. With a 4-by-3 tag on lesson 30.2's photo, the text under it moved 31.6 px.

Lesson 19.2 kept a box for a video embed with aspect-ratio, and its shift went from 0.0677 to 0. Some pages use a picture element to show a different photo on small screens. web.dev says each of its sources can carry its own width and height. Chrome reads them from the chosen source, on lines 223 to 254 of its html_image_element.cc.

Keep room for what comes late

With the photo fixed, the ad's jump was the biggest left: 0.0580. The ad network's script runs 1.9 seconds in. Ravi can't make it come sooner. But he can keep its room. He gives the empty slot a height:

A slot that keeps the ad's roomCSS
#ad { min-height: 250px; margin-top: 16px; }#ad iframe { display: block; margin: 0 auto; border: 0; }
  • Line 1 gives the slot a min-height of 250 px, the ad's height. It also moves the 16 px gap above the ad onto the slot, so the gap is there from the start.
  • Line 2 centres the ad's iframe in the slot, with no margin of its own.

min-height means "at least this tall". The empty slot keeps 250 px. If a taller ad comes, the slot can still grow. With this one rule, the ad's jump was gone. Chrome wrote no shift when the ad came in.

The font's jump got smaller too: from 0.0138 to 0.0081. Why? With the slot kept, the reviews and Add to cart sat 266 px lower, almost all below the screen. When Caveat swapped in, only the steps' own lines moved where Asha could see. Why it matters: one kept space can shrink other jumps too.

Real-life analogyA table kept for four

Meera puts a Reserved card on a table for four. If four people come, they sit, and nobody moves. If six come, she pulls up two chairs, and the next table shifts a little. If nobody comes, the table stays empty. Taking it away would make every table near it shuffle to fill the gap.

In real life: The table kept for four
In JavaScript: The slot's min-height: 250px
In real life: Four guests
In JavaScript: A 300 × 250 ad
In real life: Six guests, and two more chairs
In JavaScript: A taller ad that grows the slot
In real life: Taking the empty table away
In JavaScript: Removing the slot when no ad comes

Ad networks often send ads of more than one size. So what happens when the ad doesn't match the slot? Ravi tried other answers from the ad server, on the fixed page:

The same slot, six answersPop out in the code editor (opens in a new tab)JavaScript
// The slot keeps 250 px. What the ad server sent, and Chrome's score.const answers = [  ["a 300 × 250 ad", 0],  ["a 320 × 50 ad", 0],  ["a 336 × 280 ad", 0.0015],  ["a 300 × 600 ad", 0.0172],  ["no ad, the slot kept", 0],  ["no ad, the slot removed", 0.058],];for (const [answer, score] of answers) console.log(`${answer}: ${score === 0 ? "nothing moved" : `score ${score.toFixed(4)}`}`);
  • Line 1 says what the numbers are.
  • Lines 3 to 8 are six recorded loads: the ad that fit, a smaller ad, two taller ads, and two with no ad at all.
  • Line 10 prints one line per load. The first is a 300 × 250 ad: nothing moved. The last is no ad, the slot removed: score 0.0580.
Asha's screen on the fixed page after the ad server answered, with the slot keeping 250 px. 300 × 250 ad: nothing moved. 336 × 280 ad: score 0.0015. No ad, kept: nothing moved. No ad, removed: score 0.0580.300 × 250 adThe fixed page with 300 × 250 ad: nothing movednothing moved336 × 280 adThe fixed page with 336 × 280 ad: score 0.0015score 0.0015No ad, keptThe fixed page with no ad, kept: nothing movednothing movedNo ad, removedThe fixed page with no ad, removed: score 0.0580score 0.0580
Real screenshots from the recording, after the ad server answered. A kept slot only moves the page when the ad is taller than the slot, or when the slot is taken away.

Take the answers one at a time:

  • A smaller ad left empty space under it, but moved nothing.
  • A taller ad grew the slot by the difference. The 336 × 280 ad pushed the reviews 30 px. The 300 × 600 ad pushed them 350 px.
  • No ad, with the slot kept, moved nothing.
  • No ad, with the slot removed, moved the reviews 266 px up. It scored 0.0580: exactly the ad's score with no slot at all.

web.dev warns about that last case: "Removing the space set aside for elements can cause just as much CLS as inserting content." So which size should the slot keep? web.dev gives three choices:

  • The largest ad's size. Nothing moves, but a smaller ad leaves a gap.
  • The most likely size, from the ads your pages showed before.
  • The smallest size. Bigger ads then make a small jump, since min-height lets the slot grow.

Why it matters: whichever size you keep, keep the slot when no ad comes. Try it in your own browser. Only Chromium browsers, like Chrome and Edge, write layout-shift entries, so the live playgrounds measure only there:

Playground: keep a slot for the ad
What the playground does, shortenedJavaScript
slot.style.minHeight = `${kept}px`; // 0 or 250setTimeout(() => {  if (ad === null) slot.remove(); // no ad: the slot goes too  else slot.append(adBox(ad)); // an ad this many px tall}, 1000);
The ad slotlive
Add to cart
slot keptpick one
adpick one
layout shiftsnone
Try it yourself
Your browser

Pick what the ad server sends. The ad arrives a second later, the way a slow ad script would.

This runs in your browser, with the Layout Instability API. The ad is a plain box of the ad's height, and it arrives a second after your click, so the click doesn't excuse the move. Scores depend on the size of your window.

A font needs its room kept too

The font's jump was next. Lesson 20.3 built a fallback face for exactly this jump: Arial, resized to take the same room as Caveat. Ravi adds it to the page:

A fallback with Caveat's sizesCSS
@font-face {  font-family: "Caveat Fallback";  src: local("Arial");  size-adjust: 76.9402%;  ascent-override: 124.7722%;  descent-override: 38.9913%;  line-gap-override: 0%;}#steps { margin: 12px 0 0; padding-left: 36px; font: 26px/1.3 "Caveat", "Caveat Fallback", Arial, sans-serif; }
  • Lines 1 to 8 are lesson 20.3's face, named Caveat Fallback. It's made from the phone's own Arial.
  • Line 4, size-adjust, makes Arial's letters about as wide as Caveat's. Lines 5 to 7 give each line Caveat's room above and below the letters.
  • Line 9 puts the face second in the steps' list, after Caveat. Until Caveat arrives, the steps use it.

Now the steps had Caveat's room from the first paint. When Caveat swapped in, at 1.3 seconds, nothing moved. Ravi's own CLS was 0.

The jump only Chrome could see

One jump was left, inside the ad. The ad's own page has a photo with no size. When it arrived, the ad's text moved down. Ravi's script never sees it. But Chrome counts it, scaled to the ad's share of the screen: 0.0467.

Ravi can't edit the ad. It's the ad network's page. So he asks the network to give its photos a size too:

The ad's own photo, with its sizeHTML
<img id="ad-photo" src="chamomile.jpg" width="1200" height="800" alt="Chamomile tea">

Line 1 is the ad's photo, with its file's own size, 1200 by 800. With it, Chrome's own CLS was 0 too. Why it matters: the jumps inside an ad count against your page in Chrome's data. Ask for ads that keep their own content still.

A notice needs a slot too

In lesson 30.2, a Free delivery notice came in at the top of the page, 600 ms in. It pushed everything under the header down, and scored 0.1182. The same fix works: keep its room. Ravi puts an empty box at the top of the page:

A slot for the noticeCSS
#notice-slot { min-height: 112px; margin: 0 -16px; }

Line 1 keeps 112 px, the notice's height, across the whole width of the screen. At 600 ms, the script puts the notice inside it. Chrome wrote no shift. web.dev calls a box like this a placeholder. Why it matters: content may come late, but its room shouldn't.

Move things with transform, not top or height

Sometimes there's no room to keep. Then a notice can sit over the page instead. web.dev suggests it: keep the element out of the page's flow by laying it over the content. Ravi gives the bar position: fixed at the top of the screen. A fixed element sits over the page and takes no room in it. So nothing under the bar moves when it comes.

Real-life analogyA tray held over the table

A waiter brings dessert while you're still eating. He could squeeze a new plate onto the full table, and everyone would move their plates. Instead, he holds a tray over the table and lowers it into view. Nothing on the table moves.

In real life: A new plate squeezed onto the table
In JavaScript: Content added into the page's flow
In real life: A tray held over the table
In JavaScript: An element with position: fixed, over the page
In real life: Lowering the tray into view
In JavaScript: Sliding the element in with transform

Ravi wants the bar to slide down into view. Here are two ways to do it:

Two ways to slide the bar inJavaScript
notice.animate([{ top: "-112px" }, { top: "0px" }], { duration: 300, fill: "forwards" });
notice.animate([{ transform: "translateY(-100%)" }, { transform: "translateY(0)" }], { duration: 300, fill: "forwards" });
  • Line 1 changes top, from -112px to 0px, over 300 ms.
  • Line 2 makes the same slide with transform. translateY(-100%) starts the bar one bar-height above its place.

Here is what Chrome wrote for each, and for three ways to open Ravi's reviews:

What Chrome wrote for each movePop out in the code editor (opens in a new tab)JavaScript
// What Chrome wrote for each move: [entries, entries that counted, CLS].const moves = {  "the bar, slid with top": [18, 18, 0.0098],  "the bar, slid with transform": [0, 0, 0],  "the reviews, opened with height in 900 ms": [52, 23, 0.0093],  "the reviews, opened with height in 300 ms": [16, 0, 0],  "the reviews, in a sheet that slides with transform": [0, 0, 0],};for (const [move, [entries, counted, cls]] of Object.entries(moves)) console.log(`${move}: ${entries} entries, ${counted} counted, CLS ${cls}`);
  • Lines 3 and 4 are the bar. Each holds the entries Chrome wrote, how many counted, and the page's CLS.
  • Lines 5 to 7 are the reviews, opened three ways after a click.
  • Line 9 prints one line per move. The first is the bar, slid with top: 18 entries, 18 counted, CLS 0.0098.

Nothing under the bar moved. The bar itself did. A fixed element still has a place in the layout: on the screen, not in the page. Changing top moves that place in every frame. Lesson 30.2 showed the spec's rule: a move only counts if the place changed both with and without the transform. A transform only changes where the bar is drawn. The CSS Transforms spec says it plainly: transform "does not affect the flow of the content surrounding the transformed element."

Why it matters: if something has to slide, slide it with transform, and lay it over the page.

Opening the reviews after a click

Ravi's Show reviews button is different. It opens a panel inside the page, so the panel has to push Add to cart down. In lesson 30.2, it grew with a height transition of 900 ms. Lesson 30.1 showed that CLS skips shifts right after a click. But 900 ms is longer than that.

Line 5 of the example shows what happened. Chrome wrote 52 entries. It skipped the 29 that came in about the first half second, and counted the other 23. Two fixes worked:

  • A faster transition, 300 ms, finished inside the half second. Chrome wrote 16 entries and skipped them all.
  • A sheet that slides up over the page with transform made no entries at all.

Here is the sheet's CSS:

The reviews in a sheetCSS
#panel { position: fixed; left: 0; right: 0; bottom: 0; height: 300px; transform: translateY(100%); transition: transform 900ms linear; }#panel.is-open { transform: translateY(0); }
  • Line 1 fixes the panel to the bottom of the screen, 300 px tall, and moves it one panel-height down, out of sight.
  • Line 2 moves it back up when the button gives it the class is-open. The transition on line 1 makes that take 900 ms.

Add to cart never moved. web.dev's advice fits: if a click starts something slow, make its room within 500 ms. Why it matters: a click excuses only about half a second.

Grow with scaleX(), not width

Lesson 30.2's badge grew with width, and pushed the price sideways in 18 frames. The fix uses both ideas: keep the badge's space, and grow it with a transform.

A badge that grows with scaleX()CSS
#badge { width: 150px; transform: scaleX(0); transform-origin: left; }#badge.is-wide { transform: scaleX(1); transition: transform 300ms linear; }
  • Line 1 gives the badge its full 150 px from the start, then squeezes its picture to nothing with scaleX(0). transform-origin: left makes it grow from its left edge.
  • Line 2 grows the picture to full size over 300 ms.

The price sat 150 px along from the start. Chrome wrote no entry. Try the three ways to open the reviews in your own browser:

Playground: open the reviews three ways
The playground, shortenedJavaScript
button.onclick = () => {  if (how === "sheet") sheet.animate([{ transform: "translateY(100%)" }, { transform: "translateY(0)" }], { duration: 900, fill: "forwards" });  else panel.animate([{ height: "0px" }, { height: "120px" }], { duration: ms, fill: "forwards" });};new PerformanceObserver((list) => {  for (const shift of list.getEntries()) count(shift.hadRecentInput ? "skipped" : "counted", shift.value);}).observe({ type: "layout-shift" });
Show reviewslive
Ravi: fresh and sweet. Meera: my favourite.
Add to cart
Ravi: fresh and sweet. Meera: my favourite.
entries0
skipped, after your click0
counted0
Try it yourself
Your browser

Press a button to open the reviews. Then press Reset and try another way.

This runs in your browser, with the Layout Instability API. Your click starts each move, so entries in about the first half second are skipped. Scores depend on the size of your window.

Give skipped content a size

Ravi's page has grown. It now lists 40 reviews. Lesson 28.2 showed how content-visibility: auto saves work on long pages. The browser skips the inside of an element that's far from the screen: no style, no layout, no paint. It draws it when it comes near. Ravi tries it on two pages:

Two pages of reviewsCSS
.review { margin-top: 12px; content-visibility: auto; }.review { margin-top: 12px; content-visibility: auto; contain-intrinsic-size: auto 120px; }
  • Line 1 is the first page. Each review gets content-visibility: auto, and nothing else.
  • Line 2 is the second page. It adds contain-intrinsic-size: auto 120px.

A skipped element is sized as if it were empty. The CSS Containment spec calls this size containment. For a review, empty means 0 px tall. contain-intrinsic-size gives it a size to use instead: a guess. Here is what happened on load:

The two pages on loadPop out in the code editor (opens in a new tab)JavaScript
// The two reviews pages on load, from the recording.const noSize = { drawn: 40, cls: 0.1345 };const withSize = { drawn: 16, cls: 0 };for (const [page, { drawn, cls }] of Object.entries({ noSize, withSize }))  console.log(`${page}: Chrome drew ${drawn} of the 40 reviews at load. CLS ${cls}.`);
  • Lines 2 and 3 hold each page's recording: how many reviews Chrome drew at load, and the page's CLS.
  • Line 5 prints noSize: Chrome drew 40 of the 40 reviews at load. CLS 0.1345. Then it prints withSize: Chrome drew 16 of the 40 reviews at load. CLS 0.

Without a size, the load went like this:

  1. In its first layout, Chrome skipped every review. Each was 0 px tall. So the footer sat 600 px down, on Asha's screen.
  2. Then Chrome checked which reviews were near the screen. Piled up at 0 px, all 40 were. So it drew all 40, at 22 ms.
  3. The page grew to 5,120 px, and the footer dropped to 5,000 px. Chrome wrote a layout shift for the footer: 0.1345.

That was the page's whole CLS: "needs improvement", from a line of CSS meant to save work. And it saved nothing at load: Chrome drew every review. The course loaded the page again with Chrome's screenshots on. The first one, at 27 ms, already shows the reviews. Chrome counted the shift anyway.

With a guess, each skipped review was 120 px tall, not 0. The page was long from the start, and the footer was never near the screen. Chrome drew only the 16 reviews near the screen. Nothing moved.

Four maps of the reviews page, drawn to scale. Beside each page, a shaded bar shows Asha's screen; inside it, a shaded band shows the footer. No size: first layout page 720 px, footer at 600 px. No size: at 1 s page 5,120 px, footer at 5,000 px. auto 120px: at 1 s page 5,360 px, footer at 5,240 px. auto 120px: at the end page 5,120 px, footer at 5,000 px.No size:first layoutpage 720 pxfooter at 600 pxNo size:at 1 spage 5,120 pxfooter at 5,000 pxauto 120px:at 1 spage 5,360 pxfooter at 5,240 pxauto 120px:at the endpage 5,120 pxfooter at 5,000 px
Drawn to scale. The narrow shaded bar beside each page is Asha's screen, 823 px tall. The shaded band inside the page is the footer. Without a size, the first layout fit the whole page, footer and all, on her screen.

Was 120 px a good guess? The reviews are 80 to 152 px tall, 110 px on average. So the second page started 240 px too tall: 5,360 px instead of 5,120. As Asha scrolled, Chrome drew each review, and the page shrank to its real height. The scrollbar's thumb grew a little as it did.

How tall each page wasPop out in the code editor (opens in a new tab)JavaScript
// How tall each reviews page was, in px: [before Asha scrolled, after the last turn of the wheel].const plain = [5120, 5120];const noSize = [5120, 5120];const withSize = [5360, 5120];for (const [page, [start, end]] of Object.entries({ plain, noSize, withSize }))  console.log(`${page}: ${start} px, then ${end} px`);
  • Line 1 says what the numbers are: before Asha scrolled, and after the course's last turn of the wheel.
  • Line 2 is a third page, with no content-visibility at all. It shows the real height.
  • Line 6 prints plain: 5120 px, then 5120 px, noSize: 5120 px, then 5120 px and withSize: 5360 px, then 5120 px.
Real-life analogyA book that guesses its page count

Asha reads an e-book. Before she opens a chapter, the reader guesses its length, and shows "page 3 of 210". As she reads on, it learns each chapter's real length, and the count settles at 200. If it guessed 0 pages for every chapter, it would first say "page 3 of 3". Then it would jump to 200.

In real life: A chapter's guessed length
In JavaScript: contain-intrinsic-size: 120px, for a skipped review
In real life: Guessing 0 pages
In JavaScript: No contain-intrinsic-size: a skipped review is 0 px tall
In real life: Remembering a chapter's real length once read
In JavaScript: auto: the last remembered size
In real life: The page count
In JavaScript: The page's height, which the scrollbar shows

What does auto do? The CSS Sizing spec says the browser keeps an element's size once it has drawn it: its last remembered size. While the element is skipped, auto uses that size instead of the guess. So a review Asha has scrolled past keeps its real height.

There's a surprise in line 3, though. The first page had no contain-intrinsic-size at all. Yet once Chrome had drawn its reviews, they kept their real heights while skipped. The CSS Working Group decided that content-visibility: auto "forces contain-intrinsic-size to gain an auto value". Chrome does this on lines 1396 to 1398 of its style_adjuster.cc. So a review remembers its size once it has been drawn. Before that, it has no size to remember. That moment is what the guess is for.

Chrome draws a review when it comes within 150% of the screen's height, as lesson 28.2 found. So while Asha scrolled, every review was drawn before she reached it, and nothing jumped. Why it matters: with content-visibility: auto, always add a guess close to the real size, with auto. Without one, the first layout can jump.

Scroll the recorded pages yourself, one turn of the wheel at a time:

Playground: scroll Ravi's 40 reviews
The page5,120 px
scrolled0 px
page height5,120 px
footer at5,000 px
reviews drawn16 of 40
CLS of the load0.1345
Try it yourself
No size

After 0 turns of the wheel, Asha is 0 px down a page 5120 px tall. Chrome has drawn 16 of the 40 reviews.

Real loads in Chrome on Asha's 412 × 823 px screen. The course turned the mouse wheel 600 px at a time, and read the page 400 ms after each turn.

Which fix fits?

Here is every jump in this lesson, with its fix. Read each row across: the jump, the fix, and the score before and after.

Every jump, and the fix that took it away
The jumpThe fixBeforeAfter
The photo pushed the steps down.width and height on the photo's tag.0.1829.No shift.
The ad pushed the reviews down.A slot with min-height: 250px.0.0580.No shift.
Caveat made the steps a line shorter.A fallback face with Caveat's sizes.0.0138.No shift.
The ad's own photo pushed its text down.width and height on the ad's photo.0.0467, in Chrome's own CLS.No shift.
The notice pushed the page from the top.A slot kept at the top for it.0.1182, in lesson 30.2.No shift.
The bar slid in by changing top.The same slide with transform.0.0098.No shift.
The reviews opened with height over 900 ms.A sheet that slides up with transform.0.0093.No shift.
The footer dropped when Chrome drew 40 reviews.contain-intrinsic-size: auto 120px.0.1345.No shift.

Now sort some new jumps by the fix that suits them:

Which fix fits?
  • A product photo with width: 100% and no width or height
  • A video with no width or height
  • A map from another site, in an iframe whose box has no height
  • An ad slot that the ad network fills two seconds in
  • Reviews from fetch() that fill a section above Add to cart
  • A cookie notice that slides up over the bottom of the screen
  • A toast that slides in by changing bottom
  • A New badge that grows with width next to a price
  • 200 tea cards, each with content-visibility: auto
  • Comments far down a post, each with content-visibility: auto
Try it yourself
0 of 10 correct

Sort each jump by the fix that suits it.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common mix-ups

  • "width and height on an img make it that many pixels wide." No. With CSS like width: 100%, the CSS wins. The attributes give the shape: aspect-ratio: auto 1600 / 1067.
  • "A slot with min-height stops every jump." No. A taller ad still grows it. The 336 × 280 ad pushed the reviews 30 px, and the 300 × 600 ad pushed them 350 px.
  • "If no ad comes, remove the empty slot." No. Removing it moved the reviews 266 px up. It scored 0.0580, as much as the ad pushing in.
  • "An element over the page can't shift." No. The bar that slid in with top wrote 18 entries. With transform, it wrote none.
  • "A transition after a click never counts." No. Only about the first half second is skipped. 23 frames of the 900 ms opening counted.
  • "content-visibility only saves work, so it can't move anything." No. Without contain-intrinsic-size, the footer dropped on load, and CLS was 0.1345.
  • "contain-intrinsic-size has to be exact." No. It's only used until a review is drawn. A guess of 120 px, for reviews of 80 to 152 px, gave a CLS of 0.

Practice exercises

Answer first, then use the hints.

Exercise 1 · Warm-upThe ad's own photo

The ad network adds width and height to its photo. What does the last line print?

Starter codePop out in the code editor (opens in a new tab)JavaScript
// The ad's photo: width="1200" height="800". The ad's frame is 300 px wide.
const shown = 300;
const kept = shown * (800 / 1200);
console.log(`The ad keeps ${kept} px for its photo.`);

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upA taller ad

    The ad server sends an ad 480 px tall into Ravi's 250 px slot. What does the last line print?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    // The slot keeps 250 px. The ad server sends a 320 × 480 ad.
    const slot = 250;
    const ad = 480;
    const pushed = Math.max(slot, ad) - slot;
    console.log(`Everything under the slot moves ${pushed} px down.`);

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeWhen the guess stops mattering

      In the scroll playground, pick auto 120px. After which turn of the wheel is the page first its real height, 5,120 px?

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeTwo windows

        In the fix playground, pick + ad slot. How many milliseconds apart were the page's one shift and the ad's own jump?

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeThe ratio in DevTools

          Open the course's copy of the fixed photo in Chrome. Select the photo in DevTools. How many times does aspect-ratio appear in its Attributes Style?

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeWhen the size is remembered

            In the CSS Box Sizing spec, at what moment does the browser record an element's last remembered size?

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask which fix it's about: a shape, a slot, a transform, or a size for skipped content.

              The fixing layout shifts quiz · 8 questionsScore: first tries count
              1. Question 1 of 8What does the third line of the fix ladder print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                // Ravi's page after each fix, recorded in Chrome: [the fix, his page's CLS, Chrome's own CLS].
                const steps = [
                  ["as it was", 0.2546, 0.3013],
                  ["the photo's size", 0.0717, 0.1184],
                  ["a slot for the ad", 0.0081, 0.0467],
                  ["a fallback with Caveat's sizes", 0, 0.0467],
                  ["the ad's photo size", 0, 0],
                ];
                for (const [fix, page, chrome] of steps) console.log(`${fix}: ${page} on the page, ${chrome} in Chrome`);

                Choose an answer to see the explanation.

              2. Question 2 of 8What does the slot example print for the 336 × 280 ad?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                // The slot keeps 250 px. What the ad server sent, and Chrome's score.
                const answers = [
                  ["a 300 × 250 ad", 0],
                  ["a 320 × 50 ad", 0],
                  ["a 336 × 280 ad", 0.0015],
                  ["a 300 × 600 ad", 0.0172],
                  ["no ad, the slot kept", 0],
                  ["no ad, the slot removed", 0.058],
                ];
                for (const [answer, score] of answers) console.log(`${answer}: ${score === 0 ? "nothing moved" : `score ${score.toFixed(4)}`}`);

                Choose an answer to see the explanation.

              3. Question 3 of 8Ravi's photo tag has width="1600" and height="1067", and his CSS says width: 100% and height: auto. What does Chrome do with the two attributes?

                Choose an answer to see the explanation.

              4. Question 4 of 8The ad server sends no ad. What should the page do with the empty slot?

                Choose an answer to see the explanation.

              5. Question 5 of 8Why did the bar that slid in with transform write no layout shifts?

                Choose an answer to see the explanation.

              6. Question 6 of 8A tap opens a panel with a 300 ms height transition. Do its layout shifts count toward CLS?

                Choose an answer to see the explanation.

              7. Question 7 of 8Ravi gives his reviews content-visibility: auto and no contain-intrinsic-size. What happened when the page loaded in Chrome?

                Choose an answer to see the explanation.

              8. Question 8 of 8What does the auto in contain-intrinsic-size: auto 120px do?

                Choose an answer to see the explanation.

              Key takeaways

              • Fix the biggest jump first. On Ravi's page, the photo's size alone took CLS from 0.2546 to 0.0717.
              • width and height on an img or a video become an aspect ratio. Boxes with no attributes get aspect-ratio in CSS.
              • Keep a slot for ads and notices with min-height. Keep it when nothing comes: removing it moves the page too.
              • A fallback font with the web font's sizes keeps the words' room. Ask ad networks for ads that keep still too.
              • Slide with transform, and lay late notices over the page. A click excuses only about half a second.
              • With content-visibility: auto, add contain-intrinsic-size: auto and a guess. Without it, the first layout can jump.

              Remember the one-liner.
              Give late content its room before it arrives, and move things without changing anyone's place.

              Sources

              The facts on this page come from these specs, docs and source files:

              Coming next: Debugging CLS. Finding which element moved and why, in DevTools and in data from real visits, including jumps long after the load.

              CompleteFrontend Clear concepts. Working examples.