completefrontend
Open lab My progress
THE WEB PERFORMANCE FIELD GUIDE

Debugging CLS

Find which element moved and why: read CLS attribution from real visits, the Layout shifts track in DevTools, and jumps while scrolling and in SPAs.

By the end, you can
  • 01
    Read a CLS report from the fieldSend web-vitals' attribution with each visit's CLS, and read what moved, when, and how far the page had loaded.
  • 02
    Watch the jump in DevToolsMake the jump happen in the lab, find it on the Layout shifts track, and read its sources to find what made room.
  • 03
    Catch jumps after the loadFind jumps that come while visitors scroll, or as they move between the pages of a single-page app.

A jump that came after the load

In lesson 30.3, Ravi fixed every jump on his mint tea page. His test loads the page in Chrome. Its CLS is now 0. CLS, Cumulative Layout Shift, is Chrome's score for how much a page jumps.

Then Ravi adds his customers' reviews under Add to cart. Ben's review has a photo of his glass of tea.

Asha opens the page on her phone. She reads the brewing steps, then scrolls down to the reviews. She stops at Ben's review. A moment later, the review under it drops down her screen.

Ravi's page sends him its CLS after every visit, as in lesson 30.1. Here are two loads of the same page: his test, and Asha's visit.

Two loads of the same pagePop out in the code editor (opens in a new tab)JavaScript
// Two loads of the same page, recorded in Chromeconst loads = [  { who: "Ravi's test", scrolled: "no", cls: 0 },  { who: "Asha's visit", scrolled: "yes", cls: 0.1486 },];for (const load of loads) {  console.log(`${load.who}: scrolled ${load.scrolled}, CLS ${load.cls}`);}
  • Line 1 is a comment. The course loaded the page both ways in Chrome.
  • Lines 3 and 4 hold the two loads. Ravi's test loads the page and waits. Asha scrolls, like a real reader.
  • Lines 6 to 8 print one line per load: Ravi's test: scrolled no, CLS 0 and Asha's visit: scrolled yes, CLS 0.1486.

0.1486 is over 0.1, so it "needs improvement". Ravi has two questions. Which element moved, and what made it move? And why didn't his own test see it? Here is Asha's screen just before the jump, and just after it:

Two real frames of Asha's screen on Ravi's reviews page, cut to their top part. At 4,609 ms, she has stopped at Ben's review, and Ana's review sits right under its text. At 4,919 ms, Ben's photo has arrived and Ana's review has dropped 234.7 px down the screen.4,609 ms4,609 ms: Asha stops at Ben's review. His photo's spot: 0 px tall.Asha stops at Ben's review.His photo's spot: 0 px tall.4,919 ms4,919 ms: Ben's photo arrives. Ana's review drops 234.7 px.Ben's photo arrives.Ana's review drops 234.7 px.
Real frames from the course's recording in Chrome, cut to the top of the screen. Times count from the moment the page started loading. Everything under Ben's text moved down by the height of his photo.

Ben's photo came in with no size, and everything under it moved down. That's the answer. But Ravi doesn't know it yet. All he has is a number. This lesson follows him from the number to the photo.

Real-life analogyA complaint card with a table and a time

A customer leaves a card at the Leaf and Kettle: "My cup slid off table 5 at 2:15." The card says where and when. It doesn't say why. So Meera sets table 5 the same way and watches at 2:15. A waiter squeezes a new chair in beside it, and the table moves.

In real life: The customer's card
In JavaScript: A report from a real visit: the field data
In real life: "Table 5"
In JavaScript: What moved: largestShiftTarget
In real life: "At 2:15"
In JavaScript: When: largestShiftTime
In real life: Setting table 5 again and watching
In JavaScript: Making the jump happen in the lab, in a DevTools trace
In real life: The new chair squeezed in beside it
In JavaScript: What made room: just above what moved
The main idea

Debugging CLS means answering two questions: what moved, and what made room for it? Every layout shift lists what moved. A report from a real visit tells you where and when. A trace lets you watch it happen. Then you look just above what moved.

The rest of the lesson takes those steps in turn:

  1. Read the field report: what moved, when, and how far the page had loaded.
  2. Make the jump happen in the lab, and watch it on the Layout shifts track.
  3. Read the shift's sources, and look just above them.
  4. Look for the jumps that come late: while scrolling, and in single-page apps.

How the course recorded it

  • The browser: Chrome 157, on a screen the size of Asha's phone: 412 px wide and 823 px tall.
  • The network: the course's own server held some files back, the way a slow phone network would. Lesson 30.2's page had the same holds as before. Ben's photo waited 1.5 seconds.
  • The reports: each page ran the web-vitals library, version 6.2.3. It sent CLS to the course's server when the page was hidden. Asha "left" each page by going to another one.
  • Scrolling and clicking: the course turned the mouse wheel and clicked the mouse through DevTools' protocol. The protocol passes each turn of the wheel on at the next frame. So the lesson times each turn by when the page really scrolled.

Reading the field report

Ravi starts with the clue he has: the report from Asha's visit. A number alone can't tell him what to fix. So his page uses web-vitals' attribution build, from lesson 12.1. It adds an object called attribution to each report: notes on what moved. Here is how his page sends it:

Sending CLS with its attributionJavaScript
// The page loads web-vitals' attribution build first, as webVitals.webVitals.onCLS((metric) => {  const { largestShiftTarget, largestShiftTime, loadState } = metric.attribution;  const report = { cls: metric.value, id: metric.id, largestShiftTarget, largestShiftTime, loadState };  navigator.sendBeacon("/cls", JSON.stringify(report));});
  • Line 1 is a comment. The attribution build gives the page an object called webVitals.
  • Line 2 asks for CLS. web-vitals calls the function when the page is hidden: when Asha switches tabs, closes it, or goes to another page.
  • Line 3 takes three notes out of the attribution. Line 4 puts them in a report, with the CLS and the report's id.
  • Line 5 sends it with sendBeacon. That still gets out as the page closes, as lesson 12.3 showed.

The notes are about one layout shift: the biggest one in the burst that became the page's CLS. Lesson 30.1 called that burst a session window. The attribution has six fields:

  • largestShiftTarget: the first element in that shift's list of what moved. It's written as a CSS selector, a short text that points at an element, like #review-15.
  • largestShiftTime: when the shift happened, in milliseconds (ms) from the start of the page load.
  • largestShiftValue: that one shift's score.
  • loadState: how far the page had loaded at that moment.
  • largestShiftSource and largestShiftEntry: the browser's own records of that element and that shift, for when you need more.

Here is the report Ravi's server got from Asha:

Asha's reportPop out in the code editor (opens in a new tab)JavaScript
// The report Ravi's server got when Asha left the pageconst report = { cls: 0.1486, largestShiftTarget: "#review-15", largestShiftTime: 4910.5, largestShiftValue: 0.1486, loadState: "complete" };const share = report.largestShiftValue / report.cls; console.log(`The biggest jump moved ${report.largestShiftTarget} at ${report.largestShiftTime} ms.`);console.log(`It was ${Math.round(share * 100)}% of the CLS.`);console.log(`Load state: ${report.loadState}`);
  • Line 2 holds the report, as the server got it.
  • Line 3 works out the biggest shift's share of the CLS.
  • Lines 5 to 7 print The biggest jump moved #review-15 at 4910.5 ms., It was 100% of the CLS. and Load state: complete.

One jump made all of Asha's CLS. It moved #review-15: Ana's review, the one under Ben's. web-vitals names an element by walking up the page to the first element with an id. This review has its own id, so the name is short.

During the load, or after it?

loadState has four values. web-vitals picks one by comparing the shift's time with the page's own milestones, from lesson 5.1:

  • loading: the browser was still reading the HTML.
  • dom-interactive: the HTML was read, but DOMContentLoaded hadn't started.
  • dom-content-loaded: DOMContentLoaded had started, but images and other files were still coming.
  • complete: the page had finished loading.

Ravi puts Asha's report next to one from lesson 30.2's page:

Two reports, two load statesPop out in the code editor (opens in a new tab)JavaScript
// The biggest jump in two reports, and how far each page had loadedconst reports = [  { page: "Lesson 30.2's page", target: "#steps", time: 713.6, loadState: "dom-content-loaded" },  { page: "Asha's visit", target: "#review-15", time: 4910.5, loadState: "complete" },];for (const r of reports) {  const when = r.loadState === "complete" ? "after the load" : "during the load";  console.log(`${r.page}: ${r.target} at ${r.time} ms, ${when}`);}
  • Lines 2 to 5 hold the biggest jump from each report.
  • Line 7 turns the load state into words. Line 8 prints one line per report.
  • It prints Lesson 30.2's page: #steps at 713.6 ms, during the load and Asha's visit: #review-15 at 4910.5 ms, after the load.

Asha's page had finished loading at 2,528.5 ms. Her jump came about 2.4 seconds later. Why it matters: a jump during the load shows up when you reload the page in a test. A jump after it only shows up if you use the page, the way the visitor did.

One visit can send more than one report

web-vitals calls back each time the page is hidden, not once per visit. And Chrome may keep a page you left in its back/forward cache, ready for the Back button. The course left lesson 30.2's page, pressed Back, and left again:

Leaving, coming back, and leaving againPop out in the code editor (opens in a new tab)JavaScript
// Two reports from one tab: Asha leaves, presses Back, and leaves againconst reports = [  { cls: 0.2546, navigationType: "navigate", id: "v6-1794569594998-2377225040134" },  { cls: 0, navigationType: "back-forward-cache", id: "v6-1794569599802-6272119206044" },];for (const r of reports) console.log(`${r.navigationType}: CLS ${r.cls}`);console.log(`The same id? ${reports[0].id === reports[1].id}`);
  • Lines 2 to 5 hold the two reports the server got.
  • Line 6 prints navigate: CLS 0.2546 and back-forward-cache: CLS 0.
  • Line 7 prints The same id? false.

Chrome restored the page just as Asha had left it, with nothing left to load. So nothing moved. web-vitals treats the restored page as a new visit, with a new id and a CLS that starts at 0. Why it matters: count reports by their id, and read navigationType before you blame a page.

Here are the real reports. Pick one to see every field the server got:

Playground: the reports Ravi's server got
A report/story/
page/story/
value (CLS)0.2546
ratingpoor
navigationTypenavigate
sent at4,254.4 ms, page hidden
largestShiftTarget#steps
largestShiftTime713.6 ms
largestShiftValue0.1829
loadStatedom-content-loaded
Try it yourself
CLS 0.2546, poor

Chrome loaded lesson 30.2's page, and Asha left. The biggest jump was the photo's, during the load.

Real reports from web-vitals' attribution build, as the course's server got them. Times count from the moment the page started loading.

Watching it on the Layout shifts track

A report is a clue, not an answer. web.dev puts it plainly: "You can't fix layout shifts that you can't reproduce." To reproduce a jump is to make it happen again, where you can watch it.

Ravi starts with a jump he knows: lesson 30.2's page, before its fixes. Its jumps all came during the load. So he opens DevTools' Performance panel, from lesson 7.1, and records a reload. DevTools draws the recording as a trace, in rows called tracks. One row is the Layout shifts track.

On it, each layout shift is a purple diamond. A bigger diamond means a bigger score. Shifts close together sit on one purple line, called a cluster. Hover over a diamond, and DevTools highlights what moved on the page. Click it, and the Summary below shows its time, its score, the elements that moved, and possible culprits.

Real-life analogyA doorbell camera's timeline

Ravi's shop has a doorbell camera. Its app shows the day as a line. Each time something moves at the door, it adds a mark there. A big movement gets a big mark. Movements close together make one clip. Tap a mark, and the app plays what moved.

In real life: A mark on the day's line
In JavaScript: A diamond: one layout shift
In real life: A big mark for a big movement
In JavaScript: A big diamond for a high score
In real life: Marks close together, in one clip
In JavaScript: A cluster: shifts less than a second apart
In real life: Tapping a mark to watch it
In JavaScript: Clicking a diamond: the Summary, and a replay of the shift

Behind the panel, the trace holds Chrome's own record of each shift: a LayoutShift event. Here are the events from the course's trace:

The trace's LayoutShift eventsPop out in the code editor (opens in a new tab)JavaScript
// Chrome's LayoutShift events in the trace of lesson 30.2's pageconst shifts = [  { ms: 713.6, score: 0.18289, frame: "page" },  { ms: 1341, score: 0.01378, frame: "page" },  { ms: 1920.4, score: 0.05795, frame: "page" },  { ms: 2533.9, score: 0.04667, frame: "ad" },];const cluster = shifts.reduce((sum, shift) => sum + shift.score, 0);console.log(`The biggest diamond: ${Math.max(...shifts.map((shift) => shift.score))}`);console.log(`The cluster: ${cluster.toFixed(4)}`);
  • Lines 3 to 6 hold the four events: when, their score, and which document they were in.
  • Line 6 was inside the ad's iframe. Its score is scaled to the ad's share of the screen, as lesson 30.2 showed.
  • Line 8 adds the scores up. Line 9 prints The biggest diamond: 0.18289, the photo's jump. Line 10 prints The cluster: 0.3013.

The four shifts came less than a second apart, so DevTools drew one cluster. Its score is Chrome's own CLS for the page, from lesson 30.2. DevTools' source shows how it builds clusters:

  • It uses CLS's session window rules. A gap of a second ends a cluster, and none runs past 5 seconds.
  • A cluster also ends at a navigation, when a new page starts.
  • It leaves out shifts right after a click, tap or key press. CLS skips those too.
  • It counts shifts inside iframes, scaled down, like Chrome's own CLS.

Now Asha's jump. Her report said complete, so a reload won't show it. Ravi's test loaded the page and waited, and nothing moved. So Ravi records the way Asha used the page. He presses Record, scrolls down to Ben's review, waits, and stops. Here are both recordings, on one time scale:

Two Layout shifts tracks on one time scale, 0 to 6 seconds. Top, a reload of lesson 30.2's page: diamonds at 713.6 ms (0.1829), 1,341 ms (0.0138), 1,920.4 ms (0.0580), 2,533.9 ms (0.0467, in the ad), all in one cluster scoring 0.3013. Bottom, a recording of Asha's scroll: the page finished loading at 2,528.5 ms, and one diamond came at 4,910.4 ms (0.1486), in a cluster of its own.Reload: lesson 30.2's page0.18290.01380.05800.0467cluster: 0.3013in the adRecord while scrolling: Asha's visitpage loaded0.1486cluster: 0.14860 s2 s4 s6 s
Each diamond is one layout shift, drawn at its time, bigger for a bigger score. A cluster's line runs from its first shift until a second passes with no new one. Top: a reload. Bottom: Asha's scroll, long after the load.

In the reload, the diamonds sit inside the load. In Asha's recording, the page finished loading at 2,528.5 ms, and the one diamond came at 4,910.4 ms. Why it matters: for a jump after the load, record while you use the page, not while you reload it.

The Insights tab has a check for this, Layout shift culprits, from lesson 7.3. It guesses a cause for the worst cluster. For Asha's recording, it named an image with no size: ben.jpg. For lesson 30.2's page, it named three: the photo, a web font, and the ad's own photo. Lesson 7.3 showed it can guess wrong, so check its guess against the sources.

Pick a recording to see each diamond and cluster, as DevTools' own code read them:

Playground: two recordings on the Layout shifts track
Layout shifts track4 diamonds
diamond at 713.6 ms0.18289: ol#steps, section#reviews, button#add
diamond at 1,341 ms0.01378: section#reviews, button#add, li, li, li
diamond at 1,920.4 ms0.05795: section#reviews, button#add
diamond at 2,533.9 ms, in the ad0.04667: p#ad-text
cluster, 713.6 ms to 3,533.9 ms0.3013, 4 shifts
Layout shift culprits guessedan image with no size: mint-tea.jpg; a web font; an image with no size: chamomile.jpg
Try it yourself
Reload: lesson 30.2's page

A reload recording: Chrome loaded lesson 30.2's page, and nobody touched it.

What DevTools' own trace engine read from the course's real traces: each diamond with its score and what moved, each cluster, and the culprits insight's guesses.

What a shift's sources tell you

A diamond tells Ravi when the page jumped. Its list of elements tells him what moved. In JavaScript, that list is the layout-shift entry's sources, from lesson 11.3. The Layout Instability spec sets its rules:

  • It lists up to five things that moved: elements, or runs of text.
  • The one that covered the most screen comes first. Chrome's own code sorts them that way.
  • Each source has a node: the element itself. And it has two boxes. previousRect is where the element was in the frame before. currentRect is where it is now.

The boxes are in CSS pixels, measured from the top-left corner of the screen, like getBoundingClientRect(). They only count the part of the element that's on the screen.

Real-life analogyTwo chalk lines for every chair

When the café closes, Meera draws a chalk line around each chair. In the morning, she draws them again. Where the lines don't match, a chair moved, and the gap shows how far. A chair with no morning line has left the room. All the moved chairs start near one corner. That's where someone put a new table.

In real life: The evening's chalk line
In JavaScript: previousRect: the box in the frame before
In real life: The morning's chalk line
In JavaScript: currentRect: the box now
In real life: The gap between the two lines
In JavaScript: How far the element moved
In real life: A chair with no morning line
In JavaScript: A currentRect of all zeros: pushed off the screen
In real life: The new table in the corner
In JavaScript: What made room: just above the first source

Here are the sources of Asha's jump, as Chrome wrote them:

The sources of Asha's jumpPop out in the code editor (opens in a new tab)JavaScript
// The sources of Asha's jump: where each one was, and where it wentconst sources = [  { node: "#review-15", previousRect: { y: 323.59, height: 128 }, currentRect: { y: 558.33, height: 128 } },  { node: "#review-17", previousRect: { y: 555.59, height: 128 }, currentRect: { y: 790.33, height: 32.67 } },  { node: "#review-16", previousRect: { y: 463.59, height: 80 }, currentRect: { y: 698.33, height: 80 } },  { node: "#review-18", previousRect: { y: 695.59, height: 127.41 }, currentRect: { y: 0, height: 0 } },];for (const { node, previousRect, currentRect } of sources) {  if (currentRect.height === 0) console.log(`${node}: pushed off the screen`);  else console.log(`${node}: down ${(currentRect.y - previousRect.y).toFixed(1)} px`);}
  • Lines 3 to 6 hold the four sources, in Chrome's order: the biggest first.
  • Line 9 checks for a box with nothing left on the screen. Line 10 subtracts the old top from the new one.
  • It prints #review-15: down 234.7 px, #review-17: down 234.7 px and #review-16: down 234.7 px. Last comes #review-18: pushed off the screen.

Three things stand out:

  • Everything moved the same distance, down. web.dev says "a large downward shift often indicates the insertion of a DOM element". Something new took 234.7 px of room.
  • #review-18's new box is all zeros. It was pushed below the bottom of the screen. All zeros in the old box means the opposite: the element came into view.
  • Nothing above Ana's review moved. So the room was made just above it.

Lesson 30.2 showed that the sources name what moved, not what made room. web.dev's advice is to look at "the DOM element immediately preceding the shifted element". In code, that's previousElementSibling:

What's just above the first source?JavaScript
new PerformanceObserver((list) => {  for (const shift of list.getEntries()) {    const moved = shift.sources[0]?.node;    const above = moved?.previousElementSibling;    console.log("Moved:", moved, "Just above it:", above);  }}).observe({ type: "layout-shift", buffered: true });
  • Line 1 watches for layout shifts, as in lesson 11.3.
  • Line 3 takes the first source's node: the one that covered the most screen.
  • Line 4 takes the element just before it on the page. Line 5 logs both.

On Asha's page, the first source was #review-15. The element just before it is #review-14: Ben's review. Inside it is his photo, with no width or height. At 352 px wide, that photo is 234.7 px tall. Why it matters: the sources point at the spot, and looking just above finds the cause.

web-vitals reads the same list. Its largestShiftSource is the first source that's an element, not a run of text. largestShiftTarget is that element's selector. So Asha's report named the review that covered the most screen.

Try it in your own browser. Each change happens a little after your click, so the click doesn't excuse it:

Playground: read a shift's sources
What the playground does, shortenedJavaScript
setTimeout(change, 700);new PerformanceObserver((list) => {  for (const shift of list.getEntries())    for (const { node, previousRect, currentRect } of shift.sources)      show(node, previousRect.y, currentRect.y);}).observe({ type: "layout-shift" });
Ravi's reviewslive
Asha Fresh and sweet.
Ravi My favourite after lunch.
Meera Strong mint, and bright.
Add to cart
sourcespick a change
Try it yourself
Your browser

Pick a change. It happens 700 ms after your click, so your click doesn't excuse it.

This runs in your browser, with the Layout Instability API. The boxes' moves depend on the width of your window.

Jumps while you scroll

So why did Ravi's test miss Ben's photo? Here is the photo in the page:

Ben's review, with his photoHTML
<article class="review" id="review-14">  <div class="card"><h3>Ben</h3><p>Strong mint, and it stays bright even with honey in it.</p>    <img class="shot" src="ben.jpg" loading="lazy" alt="Ben's glass of mint tea">  </div></article>

Line 3 is the photo. loading="lazy" tells Chrome to wait until the reader scrolls near it. It has no width and no height.

Lesson 18.3 showed that on a fast connection, Chrome asks for a lazy image once it's within 1,250 px of the screen. Ben's photo sat 2,692.6 px down the page. Ravi's test never scrolled, so Chrome never asked for the photo. The test's list of files has no ben.jpg at all.

Asha did scroll. Here is her scroll, from the recording:

Asha's scroll, and the photoPop out in the code editor (opens in a new tab)JavaScript
// Asha's scroll, from the recording, in msconst lastTurn = 4606.8; // her last turn of the wheel scrolled the pageconst asked = 3407; // Chrome asked for Ben's photoconst arrived = 4909.8; // the photo arrivedconst jump = 4910.5; // the layout shiftconsole.log(`The photo took ${(arrived - asked).toFixed(1)} ms to come.`);console.log(`The jump came ${(jump - lastTurn).toFixed(1)} ms after she stopped.`);
  • Lines 2 to 5 hold four times from the recording.
  • Line 6 prints The photo took 1502.8 ms to come.
  • Line 7 prints The jump came 303.7 ms after she stopped.

Chrome asked for the photo right after Asha's second turn of the wheel. While it was on its way, she kept scrolling. She stopped with the photo's spot 297.6 px from the top of her screen. It was 0 px tall. Then the photo arrived, and everything under it moved.

Scrolling doesn't excuse a jump. The spec says a scroll isn't input. The entry's lastInputTime was 0, so hadRecentInput was false, and the jump counted in full. web.dev names this exact case: "CLS often happens while the user scrolls through a page, when lazy-loaded content loads fully without space reserved for it." Why it matters: the fix is lesson 30.3's. Give the photo its width and height.

Scroll anchoring keeps your place

Meera has an idea: show new reviews at the top of the list as they come in. Ravi worries. Asha reads further down. Won't every new review push her page? He tests it. Once Asha has stopped at Ben's review, a script adds one review at the top of the list:

A new review at the top of the listJavaScript
setTimeout(() => {  document.querySelector("#more h2").insertAdjacentHTML("afterend", '<article class="review" id="review-new"><div class="card"><h3>Kofi</h3><p>Just tried it after dinner. Cool and fresh, and not too strong.</p></div></article>');  performance.mark("new-review");}, 5600 - performance.now());
  • Line 1 sets a timer. Line 4 says when it fires: 5,600 ms after the page started.
  • Line 2 adds Kofi's review right after the list's heading, far above Asha's screen.
  • Line 3 notes the moment, for the recording.

Then he loads the page again, with one line of CSS that turns scroll anchoring off:

Scroll anchoring, turned offCSS
body { overflow-anchor: none; }

Here is what Chrome did each time:

The same new review, two waysPop out in the code editor (opens in a new tab)JavaScript
// The same new review, with scroll anchoring on and offconst loads = [  { anchoring: "on", scrollBefore: 2395, scrollAfter: 2511, cls: 0 },  { anchoring: "off", scrollBefore: 2395, scrollAfter: 2395, cls: 0.1281 },];for (const load of loads) {  const scrolled = load.scrollAfter - load.scrollBefore;  console.log(`Anchoring ${load.anchoring}: Chrome scrolled ${scrolled} px, CLS ${load.cls}`);}
  • Lines 3 and 4 hold each load: where the page was scrolled before and after, and its CLS.
  • It prints Anchoring on: Chrome scrolled 116 px, CLS 0 and Anchoring off: Chrome scrolled 0 px, CLS 0.1281.
Four real frames of Asha's screen, cut to their top part, before and after a new review goes in at the top of the list, above the screen. With overflow-anchor: auto, the default, the screen looks the same after: Chrome scrolled the page 116 px, and there was no layout shift. With overflow-anchor: none, everything on the screen moved down 116 px, a layout shift of 0.1281.overflow-anchor: autooverflow-anchor: none4,929 ms4,929 ms: Asha reads.Asha reads.5,608 ms5,608 ms: Nothing moved. scrolled 116 pxNothing moved.scrolled 116 px4,924 ms4,924 ms: Asha reads.Asha reads.5,605 ms5,605 ms: All moved 116 px. CLS 0.1281All moved 116 px.CLS 0.1281
Real frames from two loads of the same page. Left: with scroll anchoring, Chrome scrolled down by the new review's height, so the screen didn't change. Right: with it turned off, everything Asha was reading moved down.

With the usual CSS, Chrome scrolled the page down 116 px by itself. That's exactly the new review's height, with its gap. So nothing on Asha's screen moved, and there was no layout shift. With anchoring off, everything on her screen moved down 116 px. One source, #review-11, had an old box of all zeros: it slid into view from above.

Real-life analogyA finger on the line you're reading

Asha reads a binder of recipes, with a finger on her line. Meera slips new recipes in at the front. The pages before Asha's finger get thicker. Her finger moves with her page, so she never loses her place. But if a page goes in below her finger, the lines under it still move away.

In real life: Asha's finger
In JavaScript: The anchor: an element near the top of the screen
In real life: New pages slipped in at the front
In JavaScript: Content added above the anchor
In real life: The finger moving with her page
In JavaScript: Chrome scrolling by the same amount
In real life: A page slipped in below her finger
In JavaScript: Content added below the anchor: it still moves things
In real life: Reading with no finger
In JavaScript: overflow-anchor: none

That's scroll anchoring. The CSS Scroll Anchoring spec says it works by "adjusting the scroll position to compensate for the changes outside the viewport." Here are its rules:

  • The browser picks an anchor: an element near the top of the screen.
  • When the anchor moves because something above it grew, the browser scrolls by the same amount.
  • A change below the anchor doesn't move it, so nothing is fixed. Ben's photo grew below the anchor, on the screen. That's why its jump counted.
  • No anchor is picked if the page isn't scrolled at all. Then a change at the top still pushes everything.
  • overflow-anchor: none turns it off for an element and everything inside it.

Why it matters: scroll anchoring hides changes above the screen, for free, so don't turn it off without a reason. It can't hide a change on the screen itself. Try it in a box of reviews:

Playground: scroll anchoring in a box of reviews
What the playground does, shortenedJavaScript
box.style.overflowAnchor = mode; // "auto" or "none"setTimeout(() => {  box.querySelector("ol").prepend(newReview);}, 700);
The reviews boxoverflow-anchor: auto
  1. Asha Fresh mint, cool and sweet.
  2. Ravi Fresh mint, cool and sweet.
  3. Meera Fresh mint, cool and sweet.
  4. Ben Fresh mint, cool and sweet.
  5. Ana Fresh mint, cool and sweet.
  6. Sam Fresh mint, cool and sweet.
  7. Priya Fresh mint, cool and sweet.
  8. Leo Fresh mint, cool and sweet.
  9. Kofi Fresh mint, cool and sweet.
  10. Mia Fresh mint, cool and sweet.
the review you watchedpress Add
the box scrolled on its ownpress Add
layout shifts in the boxnone
Try it yourself
Your browser

Scroll the box down a little, then press Add. Try it with each setting, and once without scrolling at all.

This runs in your browser. The box is its own scroll container, so anchoring works inside it the same way it does for a whole page.

Jumps in a single-page app

Ravi has rebuilt his tea list as a single-page app, an SPA. It loads one page. Then it draws each tea's page with JavaScript, without asking the server for new HTML. The address still changes:

The tea app's router, shortenedJavaScript
document.addEventListener("click", (event) => {  const link = event.target.closest("a[data-tea]");  if (!link) return;  event.preventDefault();  history.pushState({}, "", link.href);  show(link.dataset.tea);});
  • Line 1 listens for clicks anywhere on the page.
  • Lines 2 and 3 keep only clicks on a tea's link.
  • Line 4 stops the browser from loading a new page.
  • Line 5 changes the address with history.pushState. Line 6 draws the tea's page.

Asha lands on /teas. She clicks Mint tea at 2,034 ms. Its photo has no size. The jump comes 805.3 ms after her click, and scores 0.0828. 206.5 ms later, she clicks Green tea. Its photo jumps the same way, 604.3 ms after the click. Both came more than 500 ms after a click, so both count.

Each page alone scored 0.0828: good. But what does Ravi's report say? That depends on how the page asks:

The tea app's reportsPop out in the code editor (opens in a new tab)JavaScript
// The reports from Asha's visit to the tea appconst visit = { url: "/teas", cls: 0.1656 };const pages = [  { url: "/teas", cls: 0 },  { url: "/teas/mint", cls: 0.0828 },  { url: "/teas/green", cls: 0.0828 },];console.log(`One report for the visit: ${visit.url}, CLS ${visit.cls}`);for (const page of pages) console.log(`One report per page: ${page.url}, CLS ${page.cls}`);
  • Line 2 is web-vitals' usual report, sent when Asha left.
  • Lines 3 to 7 are the reports with one per page.
  • It prints One report for the visit: /teas, CLS 0.1656. Then come three lines that start One report per page:, for /teas, /teas/mint and /teas/green.

The usual report covers the whole visit. The two jumps came 810.8 ms apart, so they fell in one session window. CLS added them up: 0.1656, "needs improvement". And it filed all of it under /teas, the address Asha landed on. Its attribution even named a jump at 3,650.1 ms, on the green tea page.

web.dev's SPA guide says this is how the metrics first worked: "the URL associated with each metric measurement is the URL the user navigated to that initiated the page load."

Asha's visit to the tea app, one page load with three addresses: /teas, then /teas/mint from her click at 2,034 ms, then /teas/green from her click at 3,045.8 ms. Two layout shifts, at 2,839.3 ms (0.0828) and 3,650.1 ms (0.0828). One report for the visit: 0.1656, filed under /teas. One report per page: /teas 0, /teas/mint 0.0828, /teas/green 0.0828./teas/teas/mint/teas/green0.08280.0828One report for the visit:0.1656, filed under /teasOne report per page:00.08280.0828
One page load, three addresses, drawn to scale. The usual report adds the two jumps into one window and files it under /teas. With soft navigations, each page gets its own CLS.
Real-life analogyOne ticket for the whole train ride

Asha buys one train ticket at Hill Road and rides through two more stations. The rail company asks her to rate the bumpiest stretch. Her rating goes on Hill Road's record, even though the bumps came later. With a new ticket at each station, each stretch would get its own rating.

In real life: The station where she bought her ticket
In JavaScript: The address Asha landed on: /teas
In real life: The stations she rode through
In JavaScript: The app's pages: /teas/mint and /teas/green
In real life: The bumpiest stretch
In JavaScript: CLS: the worst session window
In real life: A new ticket at every station
In JavaScript: Soft navigations: one CLS per page

Chrome can now tell the pages apart. From Chrome 151, it spots a soft navigation: a move to a new page inside a single-page app. Three things must happen:

  • The visitor clicks, taps or presses a key.
  • The address changes.
  • Something new is painted.

Each soft navigation gets a soft-navigation entry. It holds the new address and a navigationId: a number for that page. Chrome wrote two: /teas/mint at 2,034 ms and /teas/green at 3,045.8 ms, each at the moment of its click. Every layout-shift entry carries a navigationId too. So you can tell which page a jump happened on.

web-vitals uses them when you pass reportSoftNavs: true. Its README says CLS "is reset to measure again separate to the first page". To keep both views, ask for CLS twice:

CLS for the visit, and CLS per pageJavaScript
// One report for the whole visit, the way CrUX's stable CLS counts itwebVitals.onCLS(sendVisit);// One report per page, soft navigations includedwebVitals.onCLS(sendPage, { reportSoftNavs: true });
  • Line 2 asks for the usual CLS: one per visit.
  • Line 4 asks for one CLS per page. Each report's navigationURL says which page it's for. web-vitals sends each page's report as soon as the next page starts.

CrUX, Chrome's field data, still files the whole visit under the first address in its usual CLS. It also publishes an experimental CLS that splits it page by page. And DevTools ends a cluster at every navigation, soft ones included. Why it matters: in an SPA, check which page a jump really happened on before you fix the first one.

Here are the tea app's real reports, both ways:

Playground: the tea app's reports
A report/teas
page/teas
value (CLS)0.1656
ratingneeds-improvement
navigationTypenavigate
sent at5,799.9 ms, page hidden
largestShiftTarget#app>p.about
largestShiftTime3,650.1 ms
largestShiftValue0.0828
loadStatecomplete
Try it yourself
CLS 0.1656, needs-improvement

web-vitals' usual report: one CLS for the whole visit, sent when Asha left. Both tea pages' jumps are in it, under /teas.

Real reports from web-vitals' attribution build, as the course's server got them. Times count from the moment the page started loading.

Which clue do you need?

Each place you can look answers some questions and not others. Read each row across: where you look, what it tells you, and what it can't.

Three places to look
Where you lookWhat it tells youWhat it can't tell you
The field report, from web-vitals' attribution buildWhich element moved in the biggest jump, when, and how far the page had loaded. It comes from real visits.What pushed it. It can't see jumps inside an ad's iframe either.
The Layout shifts track, in a DevTools traceEvery jump you made happen, its score and cluster, and what ran just before it.What real visitors did. It only shows this recording, on your computer.
A shift's sourcesUp to five things that moved, each with its box before and after.What made room. You find that by looking just above the first one.

Now sort some questions by where you'd find the answer first:

Which clue do you need?
  • Which element moves most often for real visitors
  • Whether real visitors' jumps come during the load or after it
  • Which page of a single-page app jumps for real visitors
  • What ran on the main thread just before the jump
  • Which of your jumps fall in the same cluster
  • How far each element moved, and which way
  • Whether an element was pushed off the screen
Try it yourself
0 of 7 correct

Sort each question by where you'd look first.

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

Common mix-ups

  • "If my test scores 0, real visitors get 0." No. Ravi's test scored 0. Asha scrolled, and her visit scored 0.1486.
  • "largestShiftTarget is what caused the jump." No. It's the first element that moved. Asha's report named #review-15. Ben's photo, just above it, made the room.
  • "The Layout shifts track shows every layout shift." No. Like CLS, it leaves out the shifts right after a click, tap or key press.
  • "Scrolling excuses a jump." No. A scroll isn't input. Ben's photo jumped 303.7 ms after Asha stopped, and counted in full.
  • "Scroll anchoring stops every jump while you scroll." No. It only hides changes above the anchor. Ben's photo grew below it, on the screen, and the reviews still jumped.
  • "Each page of a single-page app gets its own CLS." No. The usual report gives the whole visit one CLS, under the first address. Per-page CLS needs soft navigations and reportSoftNavs.
  • "A visit sends exactly one CLS report." No. Lesson 30.2's page sent two: one when Asha left, and one from 0 after she came back.

Practice exercises

Answer first, then use the hints.

Exercise 1 · Warm-upA shorter jump

Here are the sources of a smaller jump. What does the first line print?

Starter codePop out in the code editor (opens in a new tab)JavaScript
const sources = [
  { node: "#review-9", previousRect: { y: 410, height: 104 }, currentRect: { y: 526, height: 104 } },
  { node: "#review-10", previousRect: { y: 760, height: 120 }, currentRect: { y: 0, height: 0 } },
];
for (const { node, previousRect, currentRect } of sources) {
  if (currentRect.height === 0) console.log(`${node}: pushed off the screen`);
  else console.log(`${node}: down ${(currentRect.y - previousRect.y).toFixed(1)} px`);
}

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

    Exercise 2 · Warm-upWhen Caveat arrived

    Caveat arrived at 1,313.1 ms on Asha's page. If it had made a jump then, which load state would web-vitals report?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    // web-vitals' rule, shortened, with the times of Asha's page load
    const page = { domInteractive: 9.3, domContentLoadedEventStart: 9.3, domComplete: 2528.4 };
    function loadState(time) {
      if (time < page.domInteractive) return "loading";
      if (time < page.domContentLoadedEventStart) return "dom-interactive";
      if (time < page.domComplete) return "dom-content-loaded";
      return "complete";
    }
    console.log(loadState(1313.1));

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

      Exercise 3 · PracticeWhere the cluster ends

      In the Layout shifts track playground, pick lesson 30.2's page. At what time does its cluster end, in ms?

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

        Exercise 4 · PracticeThe first page's report

        In the tea app's reports playground, pick One report per page. When was the report for /teas sent, in ms?

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

          Exercise 5 · ChallengeClusters in the tea app

          Download the course's trace of Asha's visit to the tea app. Load it in DevTools' Performance panel. How many clusters does the Layout shifts track draw?

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

            Exercise 6 · ChallengeWhat anchoring skips

            In the CSS Scroll Anchoring spec, which two values of the position property always put an element in an excluded subtree, so it's never picked as the anchor?

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

              Check your understanding

              For each question, ask which clue it's about: the field report, the track, the sources, or a jump that came late.

              The debugging CLS quiz · 7 questionsScore: first tries count
              1. Question 1 of 7What does the third line of the sources example print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                // The sources of Asha's jump: where each one was, and where it went
                const sources = [
                  { node: "#review-15", previousRect: { y: 323.59, height: 128 }, currentRect: { y: 558.33, height: 128 } },
                  { node: "#review-17", previousRect: { y: 555.59, height: 128 }, currentRect: { y: 790.33, height: 32.67 } },
                  { node: "#review-16", previousRect: { y: 463.59, height: 80 }, currentRect: { y: 698.33, height: 80 } },
                  { node: "#review-18", previousRect: { y: 695.59, height: 127.41 }, currentRect: { y: 0, height: 0 } },
                ];
                for (const { node, previousRect, currentRect } of sources) {
                  if (currentRect.height === 0) console.log(`${node}: pushed off the screen`);
                  else console.log(`${node}: down ${(currentRect.y - previousRect.y).toFixed(1)} px`);
                }

                Choose an answer to see the explanation.

              2. Question 2 of 7What does largestShiftTarget name?

                Choose an answer to see the explanation.

              3. Question 3 of 7Ravi's test scored a CLS of 0. Asha's visit to the same page scored 0.1486. Why did the test miss the jump?

                Choose an answer to see the explanation.

              4. Question 4 of 7On DevTools' Layout shifts track, what does a bigger diamond mean?

                Choose an answer to see the explanation.

              5. Question 5 of 7One of a shift's sources has a currentRect of all zeros. What happened to that element?

                Choose an answer to see the explanation.

              6. Question 6 of 7A new review goes in at the top of the list, above the screen, while Asha reads further down. The page has the default CSS. What happens?

                Choose an answer to see the explanation.

              7. Question 7 of 7In the tea app, web-vitals' usual report gave /teas a CLS of 0.1656, though nothing on /teas itself moved. Why?

                Choose an answer to see the explanation.

              Key takeaways

              • A CLS report from the field says what moved, when, and how far the page had loaded. It doesn't say what made room.
              • Make the jump happen in the lab. Reload for jumps during the load. Use the page for jumps after it.
              • On the Layout shifts track, each diamond is one shift, sized by its score. Clusters follow CLS's session windows.
              • A shift's sources give each element's box before and after. Look just above the first one for the cause.
              • Lazy content can jump while visitors scroll, and it counts in full. Scroll anchoring only hides changes above the screen.
              • An SPA's usual CLS covers the whole visit, under the first address. Soft navigations give one CLS per page.

              Remember the one-liner.
              The browser tells you what moved; you find what made room, just above it.

              Sources

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

              Coming next: Style recalculation. How the browser matches CSS selectors to elements, what makes that slow, and how to measure it.

              CompleteFrontend Clear concepts. Working examples.