Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 35

Optimizing CLS with Layout Stability Patterns

Recommended resources

Welcome to our next lesson. Having addressed loading performance with LCP and runtime responsiveness with INP, we now turn to the final pillar of the Core Web Vitals: Cumulative Layout Shift (CLS). This metric quantifies the visual stability of a page, a crucial component of user trust. In your work on e-commerce platforms, you know that a user accidentally clicking "Buy Now" instead of "Cancel" because a button moved at the last second is not just frustrating—it's a direct path to lost sales and eroded confidence.

This lesson moves beyond simply defining CLS to arming you with the architectural patterns needed to build inherently stable layouts. You will learn to diagnose the root causes of unexpected layout shifts and implement senior-level strategies, such as the aspect-ratio and space reservation patterns, to ensure your application is predictable and safe for users to interact with from the moment it starts to render.

1. The Mechanics of Instability: Deconstructing CLS

At its core, Cumulative Layout Shift measures the impact of unexpected layout shifts on the user. A "good" CLS score is 0.1 or less. It's not just about things moving; it's about content moving without user initiation in a way that disrupts their experience. To optimize it, you must first understand how it's calculated.

A layout shift score is determined by two key factors:

  1. Impact Fraction: This measures how much of the viewport is affected by the unstable element's movement. If an element covering 50% of the screen shifts, the impact fraction is 0.5. This is why shifts happening "above the fold" are so damaging—they often affect a larger portion of the user's initial view.
  2. Distance Fraction: This measures how far the unstable element moved relative to the viewport's largest dimension (width or height). A small button jumping halfway down the screen has a large distance fraction.

The final score for a single shift is Layout Shift Score = Impact Fraction × Distance Fraction.

A crucial update to the metric is the concept of Session Windows. The browser doesn't sum up every single shift over a page's entire lifetime. Instead, it groups shifts that occur in rapid succession (bursts) into windows. Your page's final CLS score is the score of the single worst window. This means your goal isn't to eliminate every tiny micro-shift, but to prevent the large, jarring bursts of instability that typically happen during page load or after user interactions.

To get a foundational understanding of what CLS measures and its common causes, watch the introduction to this video from Chrome for Developers.

Optimize for Core Web Vitals

This video introduces CLS with a memorable analogy and lists the primary culprits behind high scores, setting the stage for the optimization techniques we'll cover.

Watch the segment from the beginning of the CLS section for a clear definition and overview of the common causes.


2. Diagnosing CLS: Finding the Shifting Elements

Before you can fix layout shifts, you have to find them. While sometimes shifts are obvious, others can be subtle. Your primary tool for this is the Chrome DevTools Performance panel.

The typical workflow is:

  1. Go to the Performance tab in DevTools.
  2. Click the record button and reload the page or perform the interaction causing a shift.
  3. Stop recording and look for the Experience track. Layout shifts are marked with red blocks.
  4. Click on a red block. The Summary tab below will show you the Cumulative score and, most importantly, the Related Node that shifted. You can hover over this node to highlight it in the main window.
The Chrome DevTools Performance panel highlights layout shifts in the "Experience" track. Selecting a shift provides a summary, including the element that moved and its score, often pinpointing culprits like "Unsized images."

This video provides a walkthrough of using DevTools to pinpoint the exact elements causing CLS.

Optimize for Core Web Vitals

This segment demonstrates how to use both the Lighthouse audit and the DevTools Performance panel to find which DOM elements are contributing to your CLS score.

Watch from this section to see a practical demonstration of finding CLS issues in DevTools.


3. Core Strategies for Layout Stability

Most CLS issues stem from a handful of common problems. By mastering the patterns to solve them, you can eliminate the vast majority of visual instability in your applications.

A. Unsized Media: The aspect-ratio Pattern

This is the most common cause of CLS. When a browser encounters an <img> tag without dimensions, it doesn't know how much space to allocate. It reserves a 0x0 box. When the image finally loads, it snaps to its correct size, pushing all content below it down.

The Fix: Always provide dimensions so the browser can reserve space before the image loads.

  1. width and height HTML attributes: This is the simplest and most powerful method. Modern browsers use these attributes to calculate the image's aspect ratio and reserve the correct amount of space, even if you override the dimensions with CSS for responsiveness.
  2. CSS aspect-ratio property: For responsive containers or elements other than images (like video embeds), you can directly set the aspect ratio in your CSS.

This definitive guide from web.dev explains the problem and solution in detail.

Optimize Cumulative Layout Shift | Articles

This article from web.dev is the canonical resource for CLS optimization. We'll focus on the section dealing with images.

Read the section Images without dimensions. Pay close attention to how modern browsers use width and height attributes to infer aspect ratio automatically. This is a critical modern browser behavior that simplifies responsive design.

The following video segment visually demonstrates the "before and after" of applying this pattern, making the concept crystal clear.

Optimize for Core Web Vitals

This part of the "Optimize for Core Web Vitals" video walks through the history of image dimensions on the web and explains why the modern aspect-ratio approach works so well.

Watch from the dive into tips. The visual demo of content shifting vs. being stable is particularly effective.

B. Dynamic Content: The Space Reservation Pattern

Ads, promotional banners, and third-party embeds are notorious CLS culprits. Much like images, they are often loaded asynchronously and injected into the DOM, pushing existing content out of the way. Your experience with e-commerce platforms makes you familiar with the frequent use of such banners.

Real-world examples from a social media feed and an e-commerce site show how dynamically loaded banners or content can push page elements down, causing a poor user experience.

The Fix: Statically reserve space for the dynamic content before it loads.

  1. Use min-height: For an ad slot or banner container, setting a min-height in CSS ensures that space is held open. The trade-off is potential empty space if the content doesn't load, but for Core Web Vitals, stability is preferable.
  2. Choose the most likely size: Based on historical data (e.g., from your analytics), you can reserve space for the most common ad or banner size to minimize the chance and magnitude of a shift.
  3. Place it below the fold: If you cannot reserve space, injecting dynamic content lower down the page reduces its initial impact, as the Impact Fraction is smaller if the user hasn't scrolled yet.

This video gives a masterclass on this, using a real-world example from the e-commerce site Chloé.

Optimize for Core Web Vitals

This case study shows how Chloé tackled CLS from a dynamic promo banner and other components by reserving space and moving data fetching to the server.

Watch from the section on dynamic content. This is a fantastic senior-level example, as it combines a simple CSS fix (height) with an architectural change (moving an API call to the server) for a comprehensive solution.

C. Web Fonts: The Font Matching Pattern

When you use web fonts, the browser often has to render text twice. First, with a fallback system font (causing a Flash of Unstyled Text or FOUT), and then again when the web font downloads. If the two fonts have different dimensions, this swap causes text to reflow and shifts the layout.

The Fix: Minimize the dimensional difference between the fallback and web font.

  1. font-display: optional: This tells the browser to only use the web font if it's available for the initial paint. If not, it sticks with the fallback for the entire session. This is the simplest way to guarantee zero font-related CLS, but at the cost of brand consistency on slow connections.
  2. size-adjust and font-face descriptors: This is the advanced, senior-level approach. The CSS @font-face rule includes descriptors like size-adjust, ascent-override, and descent-override. You can use these to tweak the fallback font's metrics to more closely match your web font, making the final swap nearly imperceptible.

This resource provides more detail on these font optimization techniques.

Optimize Cumulative Layout Shift | Articles

This section of the web.dev guide covers how font loading leads to CLS and introduces the modern tools available to mitigate it.

Focus on the section Web fonts. The key takeaway is the list of tools, especially the new APIs like size-adjust which give you fine-grained control.

D. Animations: The transform Pattern

Animations can cause layout shifts if you animate properties that affect the document flow, such as width, height, margin, or position (top, left, etc.). When these change, the browser must perform a "reflow" or "layout" calculation, which can be expensive and cause CLS.

The Fix: Animate properties that do not trigger layout.

  • Use CSS transform (translate, scale, rotate) and opacity. These changes can typically be handled by the browser's compositor on the GPU, without affecting the layout of other elements.

Optimize Cumulative Layout Shift | Articles

This short section clearly explains which animation properties to avoid and which to prefer.

Read the section titled Animations. The distinction between layout-triggering properties and transform is the central concept.


4. A Senior-Level Approach: Prioritizing Fixes

In a real-world project with finite engineering resources, you can't fix everything at once. A senior engineer doesn't just identify problems; they prioritize them based on impact and effort.

A simple but effective framework is the Impact/Effort Ratio:

Priority Instability Type Difficulty CLS Impact Action Plan
P0 (Critical) Top-of-Page Banner/Popup Low High Immediate fix. Pushes the entire viewport. Reserve space or use an overlay.
P1 (High) Unsized Hero Image Low High Easy win. Add width/height attributes or aspect-ratio CSS.
P2 (Medium) Dynamically Loaded Ad Slots Medium Medium Reserve space with min-height based on the most common ad size.
P3 (Low) Web Fonts (FOUT) High Medium Refine with size-adjust. Requires fine-tuning but solves text "jitter".

Always tackle top-down shifts first. A 20px shift caused by a banner at the top of the page has a much higher Impact Fraction (and thus a higher CLS score) than a 20px shift in the footer.


Conclusion

In this lesson, we have completed our deep dive into the Core Web Vitals by dissecting Cumulative Layout Shift. You now have a robust mental model for visual stability and a toolkit of architectural patterns to enforce it.

Key Takeaways:

  • CLS measures unexpected visual instability, calculated using Impact Fraction and Distance Fraction within session windows.
  • Diagnose shifts using the DevTools Performance panel to find the specific elements that moved.
  • Prevent shifts from unsized media by using width and height attributes or the CSS aspect-ratio property to reserve space.
  • Prevent shifts from dynamic content like ads and banners by statically reserving space with min-height.
  • Minimize shifts from web fonts by using font-display: optional or meticulously matching fallback font metrics with size-adjust.
  • Create smooth animations by animating transform and opacity instead of layout-triggering properties.
  • Prioritize fixes by focusing on high-impact, low-effort changes, especially those occurring at the top of the page.

With a firm grasp of LCP, INP, and CLS, you are now equipped to analyze and optimize the complete user experience of a web application from a performance perspective.

In our next module, we will shift gears from the performance of loading and interacting with a page to the architecture of Real-Time & Collaborative Systems. We'll begin by exploring the foundational networking protocols—WebSockets, Server-Sent Events, and Long Polling—that power live features like chats, notifications, and collaborative editing.