top of page

What is Cumulative Layout Shift (CLS) and How to Optimize For It

Aug 23, 2024

11 min read

Yossi Fest

A Deep Dive into Cumulative Layout Shift (CLS) - What It Is, How to Measure It, and How to Fix It


Cumulative Layout Shift (CLS) is a crucial metric in web performance that directly impacts user experience. Among the three Core Web Vitals—Largest Contentful Paint (LCP), Interaction to Next Paint (INP), and CLS—CLS stands out because it measures visual stability rather than speed. When users interact with a webpage, they expect the content to remain stable and predictable. However, unexpected shifts in layout can lead to frustrating experiences, such as clicking the wrong button or losing your place in a text. In this comprehensive guide, we’ll explore what CLS is, why it matters, how to measure it, where to find errors, and detailed instructions on how to fix each issue contributing to a poor CLS score.


What is CLS?

CLS is a metric that quantifies how much unexpected layout shifts affect a webpage during its lifecycle. Specifically, it measures the sum total of all individual layout shift scores for every unexpected layout shift that occurs. A layout shift happens whenever a visible element changes its position from one rendered frame to the next.


Google uses CLS as part of its Core Web Vitals to assess the overall user experience on a website. A CLS score is calculated based on two factors: the impact fraction and the distance fraction. The impact fraction measures how much of the viewport is affected by the movement of an element, while the distance fraction measures the distance the element moved, relative to the viewport.


A good CLS score is 0.1 or less, meaning that any shifts that occur are minimal and unlikely to negatively impact the user experience. Scores between 0.1 and 0.25 need improvement, while anything above 0.25 is considered poor and can lead to a frustrating user experience, potentially affecting your site's rankings on search engines.


Why CLS Matters

Visual stability is a fundamental aspect of a good user experience. When users visit your website, they expect content to remain where it is, especially as they interact with the page. Unexpected shifts can lead to negative experiences, such as misclicks, loss of context, or confusion. For example, if a user is about to click a button and the page shifts, causing them to click something else, it creates frustration and can even lead to lost conversions.


From an SEO perspective, CLS is part of the Core Web Vitals, which Google considers in its ranking algorithms. A high CLS score can negatively impact your site’s ranking, making it critical to optimize for this metric.


How to Measure CLS

Understanding and optimizing your CLS starts with accurately measuring it. Several tools can help you monitor and improve your CLS score:


  1. Google PageSpeed Insights: This tool provides a comprehensive overview of your site’s performance, including CLS. It offers a breakdown of your site’s metrics for both mobile and desktop, along with suggestions for improvement. To check your CLS using PageSpeed Insights, simply enter your website’s URL and analyze the report generated. Look for the CLS score under the “Core Web Vitals” section.

  2. Chrome DevTools: Chrome DevTools is an invaluable resource for web developers. To measure CLS using DevTools:

    • Open your website in Google Chrome.

    • Right-click anywhere on the page and select "Inspect" to open DevTools.

    • Navigate to the "Performance" tab.

    • Start recording by clicking the record button (a circular icon).

    • Interact with your site as a user would, then stop the recording.

    • Look for layout shifts in the summary view or within the "Experience" section.

  3. Web Vitals Extension: This Chrome extension provides real-time feedback on your site’s Core Web Vitals, including CLS, directly within the browser. It’s useful for quick checks and provides immediate insights into potential issues.

  4. Google Search Console: Search Console’s Core Web Vitals report is another excellent tool for monitoring your site’s performance over time. It shows which pages are affected by poor CLS and provides a detailed report on these pages.

  5. Lighthouse: Lighthouse, which is integrated into Chrome DevTools, can generate reports that include CLS. It’s particularly useful for more detailed audits and can help identify specific areas where your site might be falling short.


Top Causes of CLS and How to Fix Them

Understanding the causes of CLS is the first step toward improving it. Several common issues contribute to high CLS scores, and each requires a targeted approach to fix.


1. Images Without Dimensions

Cause: When images are added to a page without defined width and height attributes, the browser does not know how much space to reserve for them. As the images load, the browser has to adjust the layout to accommodate them, leading to shifts.


How to Check:

  • Use Chrome DevTools to inspect your page’s images. Right-click on an image and select "Inspect" to see if the width and height attributes are specified. If they’re missing, that image could be contributing to CLS.

  • Additionally, tools like PageSpeed Insights or the Web Vitals Extension can identify images lacking dimensions.


How to Fix:

  • Set Explicit Dimensions: Always define the width and height attributes for all images in your HTML or CSS. This ensures the browser reserves the appropriate amount of space for each image, preventing layout shifts as the images load.

<img src="example.jpg" width="600" height="400" alt="Example Image">
  • Use CSS Aspect Ratios: For responsive images, consider using CSS to set aspect ratios, which can help maintain the correct layout during loading.


.responsive-image { width: 100%; aspect-ratio: 3 / 2; }
  • Responsive Design Considerations: When using responsive images (e.g., using srcset for different screen sizes), ensure that the images are appropriately sized and that the dimensions adjust accordingly to prevent shifts.



2. Ads, Embeds, and Iframes Without Dimensions

Cause: Like images, ads, embeds, and iframes without defined dimensions can cause layout shifts as they load, especially if they are injected dynamically.


How to Check:

  • Inspect your page to identify ads, embeds, and iframes. Look for elements that are being loaded dynamically or are inserted late in the loading process. Use Chrome DevTools to check if these elements have defined width and height attributes.

  • Monitor the behavior of these elements as the page loads. You might notice shifts in the layout that correlate with the loading of these elements.


How to Fix:

  • Set Fixed Dimensions: Define fixed width and height for all ads, embeds, and iframes to ensure that the browser reserves enough space for them during loading.

<iframe src="example.html" width="600" height="400"></iframe>
  • Reserve Space with Placeholder: If the content is dynamic and may vary in size, reserve space with a placeholder that matches the expected dimensions of the content. This prevents shifts when the content finally loads.

.ad-slot { width: 300px; height: 250px; background-color: #f0f0f0; /* Placeholder color */ }
  • Consider Lazy Loading: For ads and embeds that are below the fold, consider lazy loading to defer their loading until they’re needed. However, make sure to reserve space for them to avoid layout shifts.


3. Web Fonts Causing FOUT/FOIT

Cause: Flash of Unstyled Text (FOUT) and Flash of Invisible Text (FOIT) occur when web fonts load slowly. During this time, fallback fonts might be used, which can cause layout shifts if the fallback font has different dimensions from the intended font.


How to Check:

  • Monitor the loading of your web fonts using Chrome DevTools or Web Vitals Extension. Look for instances where text appears to shift as the page loads.

  • Check your CSS to see how fonts are loaded and whether fallback fonts are defined.


How to Fix:

  • Use Font Display Strategies: Control how fonts are displayed using the font-display property in your CSS. Options include:

    • font-display: swap;: Displays fallback fonts until the custom font loads, minimizing layout shifts.

    • font-display: optional;: Allows the browser to use the fallback font permanently if the custom font fails to load quickly.

@font-face { font-family: 'CustomFont'; src: url('customfont.woff2') format('woff2'); font-display: swap; }
  • Optimize Font Loading: Consider preloading critical fonts to ensure they load earlier in the page lifecycle, reducing the likelihood of FOUT/FOIT.

<link rel="preload" href="customfont.woff2" as="font" type="font/woff2" crossorigin="anonymous">
  • Consistent Fallback Fonts: Use fallback fonts that closely match the size and style of your custom fonts to minimize shifts when the font changes.

body { font-family: 'CustomFont', 'FallbackFont', sans-serif; }

4. Dynamic Content (e.g., Pop-ups, Banners, etc.)

Cause: Dynamic content such as pop-ups, banners, or ads can cause layout shifts if they are added to the DOM after the initial page load, especially if they push existing content down.


How to Check:

  • Observe your page during loading and interaction phases. Pay attention to any dynamic content that appears after the page has loaded. Use Chrome DevTools to simulate different network conditions to see how content loading order affects layout stability.


How to Fix:

  • Reserve Space for Dynamic Content: One of the most effective ways to prevent layout shifts caused by dynamic content is to reserve space for it ahead of time. This can be done by allocating a specific area on the page where the content will appear. For example, if you know that a banner ad will load at the top of the page, ensure there is enough space reserved so that when the ad loads, it doesn't push content down.

.banner-placeholder { width: 100%; height: 250px; /* Allocate space for the banner ad */ background-color: #f0f0f0; }
  • This placeholder will ensure that when the banner ad loads, it doesn’t cause the page’s layout to shift.

  • Lazy Loading with Caution: While lazy loading can improve load times, it can also lead to layout shifts if not handled carefully. When implementing lazy loading for images or other dynamic content, always ensure that the layout does not shift when the content appears. You can do this by specifying exact dimensions or reserving space for the content.

  • Avoid Inserting Content Above Existing Content: Try to avoid inserting new content above existing content, as this is a common cause of layout shifts. If new content must be inserted, consider adding it below existing content or in a way that does not disturb the flow of the page.

  • Use Animation or Transition Effects: If dynamic content must be added to a page and cannot be pre-allocated, consider using CSS transitions or animations to make the appearance of new content less jarring. For instance, you can fade in new content or slide it into view, reducing the perceptual impact of the shift.

.new-content { opacity: 0; transition: opacity 0.5s ease-in-out; } .new-content.loaded { opacity: 1; }

5. Flash of Unstyled Content (FOUC)

Cause: FOUC occurs when CSS files load after the HTML, causing the page to render momentarily without styles. This can lead to layout shifts as the browser applies styles after the initial render.


How to Check:

  • You can identify FOUC by observing your site’s load behavior. If you see unstyled content for a brief moment before styles are applied, you’re experiencing FOUC. Chrome DevTools can help you trace the loading order of your CSS files and see how they affect the rendering process.


How to Fix:

  • Inline Critical CSS: One of the most effective solutions is to inline critical CSS directly into the HTML. This ensures that the most important styles are loaded and applied as soon as the HTML is parsed, preventing FOUC.

<style> /* Critical CSS inlined here */ body { font-family: Arial, sans-serif; background-color: #fff; color: #333; } </style>
  • Minimize and Consolidate CSS Files: Reduce the number of CSS files your page needs to load by consolidating them into a single file where possible. Also, minimize CSS files to reduce load times.

<link rel="stylesheet" href="styles.min.css">
  • Preload Key Stylesheets: Use the preload attribute to load important CSS files earlier in the page’s load process. This can help ensure that styles are applied sooner, reducing the chance of FOUC.

<link rel="preload" href="styles.css" as="style">
  • Use Efficient CSS Delivery: Ensure that your CSS is delivered efficiently by leveraging browser caching, optimizing file sizes, and serving files via a content delivery network (CDN). This reduces the time it takes for styles to be applied to the page.


6. Incorrect DOM Order

Cause: Incorrect DOM order refers to a situation where the visual order of elements on a webpage does not match the order in which they are defined in the DOM. This can lead to unexpected layout shifts, particularly when elements are dynamically inserted or when the page is rendered differently than expected.


How to Check:

  • To identify incorrect DOM order, inspect your webpage using Chrome DevTools. Look at the structure of the DOM and compare it to the visual layout of your page. Pay attention to any elements that are positioned out of sequence in the DOM, especially if these elements are dynamically inserted.


How to Fix:

  • Ensure Logical DOM Structure: Structure your HTML in a way that reflects the intended visual order of elements. This ensures that when the page is rendered, elements appear in the correct order and are less likely to cause layout shifts.

<header>Header Content</header> 
<main>Main Content</main>
<footer>Footer Content</footer>
  • Use CSS Flexbox or Grid for Layouts: These CSS layout models allow for more flexible and predictable layouts. By using Flexbox or Grid, you can control the visual order of elements without having to manipulate the DOM order directly.

.container { display: flex; flex-direction: column; } .header { order: 1; } .main { order: 2; } .footer { order: 3; }

This approach ensures that the visual order remains consistent with the DOM order, reducing the likelihood of layout shifts.


  • Avoid DOM Manipulation During Load: Limit the amount of DOM manipulation that occurs during the page load process. If you need to add or reorder elements dynamically, consider doing so after the page has fully loaded to avoid layout shifts during the critical rendering path.

  • Test Across Devices and Browsers: Ensure that your site’s layout is consistent across different devices and browsers. Sometimes, layout shifts can occur due to differences in how browsers render content. Use tools like BrowserStack or CrossBrowserTesting to test your site on various platforms and identify any discrepancies.


Advanced Techniques for Reducing CLS

Beyond the common fixes, there are more advanced techniques and strategies that can further optimize your site’s CLS score.


1. Prioritize Content Visibility

Ensure that critical content is loaded and visible to the user as quickly as possible. Non-essential elements, like third-party widgets or large background images, should be deprioritized or lazy-loaded to prevent them from causing layout shifts.

  • Critical Rendering Path Optimization: Focus on optimizing the critical rendering path by minimizing the number of render-blocking resources. This includes optimizing CSS delivery, deferring non-critical JavaScript, and ensuring that above-the-fold content is prioritized.


<link rel="stylesheet" href="critical.css"> <script src="non-critical.js" defer></script>

2. Use Content Delivery Networks (CDNs)

CDNs can help reduce load times by serving your content from servers closer to the user. This not only speeds up resource delivery but also reduces the likelihood of layout shifts caused by delayed content.

  • CDN Configuration: Ensure that your CDN is configured to deliver optimized and cached versions of your site’s resources. This can include images, CSS, JavaScript, and fonts.

<link rel="stylesheet" href="https://cdn.example.com/styles.css">

3. Regularly Audit and Monitor CLS

CLS optimization is not a one-time task; it requires ongoing monitoring and auditing. Regularly check your site’s performance using tools like Google PageSpeed Insights, Chrome DevTools, and Search Console to catch any new issues that may arise as your site evolves.

  • Set Up Alerts: Consider setting up performance monitoring tools that alert you when your site’s CLS score exceeds a certain threshold. This allows you to address issues promptly before they impact the user experience or SEO.

  • Conduct User Testing: Engage in user testing to observe how real users interact with your site. This can reveal layout shifts that automated tools might miss, especially on pages with dynamic or interactive content.


Wrapping Up

Cumulative Layout Shift (CLS) is a key component of the user experience, and optimizing it can have a significant impact on how users perceive and interact with your website. By understanding the causes of CLS and implementing the fixes outlined in this guide, you can reduce or eliminate layout shifts, leading to a smoother, more stable user experience.


Remember, a good CLS score is not just about passing Google’s Core Web Vitals assessment—it’s about providing a reliable and enjoyable experience for your users. By prioritizing visual stability and addressing the issues that lead to layout shifts, you can improve both user satisfaction and your site’s overall performance. Regularly monitor and audit your site, implement best practices, and stay vigilant for new issues as your site grows and changes. Your users will thank you, and so will your search rankings.

Aug 23, 2024

11 min read

bottom of page