How to Fix Cumulative Layout Shift: Reserve the Space

To fix cumulative layout shift, find out which element moved and what arrived late above it, then reserve that space before the late content loads. That means width and height on images, a min-height on any slot a script fills, and transform for anything animated. A good CLS is 0.1 or less at the 75th percentile of page loads.

The Layout Instability API that reports shifts is Chromium-only as of November 2026, so the debugging happens in Chrome or Edge. The fixes are for every browser, because the page jumps in Safari and Firefox too. The numbers below come from small test pages run in Chromium 149 on a 400 by 800 pixel viewport.

What does the CLS number measure?

Each shift gets a score: the share of the viewport covered by the elements that moved, counting their old and new positions together, multiplied by the distance they moved as a fraction of the viewport’s longer side. web.dev’s CLS reference has the diagrams.

Take a script that inserts a 100px promo banner above the content 400 ms into the load. The content fills the screen, so the impact fraction is 1. It moved 100px on an 800px viewport, so the distance fraction is 0.125. Chromium reported one shift of 0.1250. On that viewport a single 100px banner is over the 0.1 line by itself, and anything above 0.25 is rated poor.

Shifts are not added up over the life of the page. They are grouped into session windows, each a run of shifts less than a second apart and at most five seconds long, and CLS is the largest window. A test page that shifted 0.0250 at 307 ms, 0.0244 at 706 ms and 0.0594 at 2,606 ms scored 0.0594. The third shift came more than a second after the second, so it started a new window.

How do you find the element that moved?

Log every shift with its sources. Paste this into the DevTools console, or load it ahead of every other script:

// Paste into the DevTools console, or load it before any other script.
let cls = 0;
let windowValue = 0;
let windowStart = 0;
let lastShift = 0;

function describe(node) {
  if (!node) return '(removed from the DOM)';
  const el = node.nodeType === 1 ? node : node.parentElement;
  if (!el) return node.nodeName;
  const id = el.id ? `#${el.id}` : '';
  const classes = [...el.classList].map((name) => `.${name}`).join('');
  return el.tagName.toLowerCase() + id + classes;
}

new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (entry.hadRecentInput) continue;

    const sameWindow =
      windowValue > 0 &&
      entry.startTime - lastShift < 1000 &&
      entry.startTime - windowStart < 5000;

    if (sameWindow) {
      windowValue += entry.value;
    } else {
      windowValue = entry.value;
      windowStart = entry.startTime;
    }
    lastShift = entry.startTime;
    cls = Math.max(cls, windowValue);

    console.log(
      `shift ${entry.value.toFixed(4)} at ${Math.round(entry.startTime)} ms,`,
      `window ${windowValue.toFixed(4)}, CLS ${cls.toFixed(4)}`,
    );
    for (const { node, previousRect, currentRect } of entry.sources) {
      const dx = Math.round(currentRect.x - previousRect.x);
      const dy = Math.round(currentRect.y - previousRect.y);
      console.log(`  ${describe(node)} moved ${dx}px across, ${dy}px down`);
    }
  }
}).observe({ type: 'layout-shift', buffered: true });

buffered: true replays shifts from before the observer existed, so pasting it after the page has loaded still works. On the banner page it printed:

shift 0.1250 at 417 ms, window 0.1250, CLS 0.1250
  main#content moved 0px across, 100px down

The source is main#content, not the banner. sources holds up to five elements that moved, largest first, and the Layout Instability spec says an inserted element is not reported, only what it pushed. So the output names what was pushed. The likeliest cause is the element just before it in the DOM, which is where web.dev’s guide to debugging layout shifts says to look first. node is null when the element has since been removed.

Firefox 151, in the build Playwright ships, answered the same snippet with Ignoring unsupported entryTypes: layout-shift. and logged nothing else.

For a visual version, the Layout Shifts track in the DevTools Performance panel marks each shift on the timeline, and Layout Shift Regions in the Rendering tab flashes the moved areas purple.

How to fix cumulative layout shift from images, embeds and banners

Tell the browser the size before the content exists.

<img src="/img/bench.jpg" width="640" height="360" alt="Workshop bench">
<div id="promo-slot"></div>
img {
  max-width: 100%;
  height: auto;
}

#promo-slot {
  min-height: 100px;
}

The width and height attributes do not pin the image to 640 pixels. Browsers turn them into a default aspect-ratio: auto 640 / 360, so with height: auto the box is held at the right proportions at any width. On the test page a delayed image with no attributes pushed the content down 208px, a shift of 0.2522. With them there was no shift at all. With the wrong ones (640 by 480 on a 16:9 file) the page still shifted 0.0666 when the real image arrived, which is the argument for generating the attributes from the file at build time. Under srcset, every candidate needs the same ratio. For art direction, <source> takes width and height too.

The reserved slot took the banner shift from 0.1250 to nothing. It only works while the slot keeps its height: hiding it with display: none because no banner came back produced the same 0.1250 in the other direction, so an empty slot should show a placeholder instead. A banner that does not need to sit in the flow, a cookie notice for instance, can be position: fixed. That version produced no shift either.

Embeds, iframes and ad slots get the same treatment: a min-height or an aspect-ratio on the container. Where the size varies, web.dev’s CLS optimisation guide suggests reserving the smallest size the slot can return and accepting the remainder.

Do animations and web fonts count?

Animations count when they move things through layout. A bar animating height from 0 to 100px over half a second produced 13 separate shifts, 0.0547 in total, as it pushed the content down frame by frame. Animating top counted as well. The same motion written as transform: translateY() produced none, because the spec does not treat a change that is only a transform as a shift.

Fonts shift text when the web font replaces a fallback with different metrics. font-display: optional avoids the swap, since the web font is used only if it is ready at first layout. Otherwise, declare the fallback in its own @font-face and tune size-adjust, ascent-override, descent-override and line-gap-override until the two faces take up the same space.

Why does field CLS disagree with Lighthouse?

Lighthouse loads the page and stops. The Chrome UX Report measures CLS for as long as the page is open, so anything that moves while people scroll or hover is counted. Content that lazy-loads during a scroll with no reserved size is the case web.dev’s guide names.

Shifts within 500 ms of a tap, click or key press are flagged hadRecentInput and left out. Scrolling is not input. On a test page, content inserted 100 ms after a click was flagged and excluded, and the same content inserted 700 ms after it scored 0.1187. When the fetch behind a button can take longer than half a second, reserve the space in the click handler. Setting min-height straight away was flagged, and the late content then moved nothing.

Animation has the same limit. A panel opening over 0.3 seconds after a click was excluded in full. One opening over 1.5 seconds was counted from 507 ms onwards, so keep click-driven motion short. Our post on animating to height auto has the CSS for that kind of panel.

The observer and the field data part company in two more places. Shifts inside an iframe count towards the page in the Chrome UX Report but are not reported to the parent page’s observer, and a page restored from the back/forward cache starts again at zero.

To see what real visitors get, report from the field with the attribution build of web-vitals (6.2.3 here):

import { onCLS } from 'web-vitals/attribution';

onCLS(({ id, value, rating, navigationType, attribution }) => {
  navigator.sendBeacon(
    '/analytics',
    JSON.stringify({
      metric: 'CLS',
      id,
      value,
      rating,
      navigationType,
      page: location.pathname,
      target: attribution.largestShiftTarget,
      shiftValue: attribution.largestShiftValue,
      shiftTime: attribution.largestShiftTime,
      loadState: attribution.loadState,
    }),
  );
});

The callback can run more than once for a page, because it reports whenever the page is hidden, so store by id and keep the last value. loadState says when the largest shift happened. At complete it came after the load event, where a lab run that only loads the page is unlikely to catch it.

What we would do

Run the console snippet on the three templates that carry the most traffic, with a phone-sized viewport. Scroll to the bottom and click everything that loads content. Fix in order of shift size: image dimensions generated at build time, a reserved height for every slot a script fills, overlays for notices, transforms for motion. Then ship the attribution snippet and wait, because the Chrome UX Report is a 28-day rolling average and one good deploy takes weeks to show in full.

If the field number is already under 0.1, leave a 0.02 lab shift alone and spend the time on whichever metric is failing. For slow interactions that is our INP guide.

Whoooop does this as part of website speed optimisation: field measurement first, then fixes in the templates that produce the bad sessions.

Need this built properly?

Get in touch

Hack the planet!