Cumulative Layout Shift Fix
How to find and fix Cumulative Layout Shift so pages stay stable and Core Web Vitals pass.
July 9, 202614 min read
Cumulative Layout Shift (CLS) is a frustrating user experience issue on modern websites. When page elements unexpectedly shift during loading, it creates a jarring experience that can lead to accidental clicks, lost engagement, and frustrated users. As part of Google's Core Web Vitals, CLS is a critical ranking factor that impacts your website's search engine performance.
Fixing CLS issues is about creating a stable, predictable browsing experience that keeps users engaged. A poor CLS score can negatively affect your rankings and drive visitors away. This guide covers everything you need to know about implementing an effective cumulative layout shift fix, from understanding the root causes to measuring improvements and maintaining optimal performance.
Understanding Cumulative Layout Shift (CLS)
Cumulative Layout Shift (CLS) measures unexpected movement of page elements during loading. When images load without specified dimensions, ads appear suddenly, or fonts swap in after initial rendering, these events cause visible elements like text blocks, buttons, images, and navigation menus to shift unexpectedly. This disrupts user interaction and creates a frustrating browsing experience.
Consider a common scenario: a user is about to click a "Subscribe" button when an advertisement loads above it, pushing the button down. The user accidentally clicks on the ad instead. Such experiences lead to higher bounce rates, reduced user trust, and decreased conversions.
CLS is measured using a formula that combines the impact fraction (viewport affected by the shift) and the distance fraction (how far elements move). For example, if an element takes up 50% of the viewport and moves down by 25% of the viewport height, the CLS score would be 0.5 × 0.25 = 0.125. A good CLS score is 0.1 or less, meaning minimal unexpected movement during page loading.
CLS is a ranking factor in Google's search algorithm. Websites with optimized CLS scores perform better in search results, making this metric important for user satisfaction and SEO success. For any website owner serious about providing excellent user experience and maintaining competitive search rankings, understanding and fixing CLS issues should be a priority.
Common Causes of CLS
Understanding layout shift triggers is essential for implementing effective fixes. Here are the primary culprits behind CLS issues:
- Images without dimensions: When browsers encounter images without specified width and height attributes, they can't reserve the appropriate space during initial rendering. As images load, they push surrounding content down or to the side, creating significant layout shifts.
- Ads, embeds, and iframes without reserved space: Third-party ads, social media embeds, and iframe elements load asynchronously after the main page content. Without pre-allocated space, these elements push existing content when they appear.
- Fonts causing FOIT/FOUT: Flash of Invisible Text (FOIT) occurs when custom fonts haven't loaded, leaving text invisible until the font arrives. Flash of Unstyled Text (FOUT) happens when fallback fonts appear first, then get replaced by custom fonts, causing text reflow and layout shifts.
- Dynamically injected content: Content inserted into the DOM after initial page load (like notification banners, cookie consent pop-ups, or dynamically loaded product recommendations) can cause substantial layout shifts if not properly managed.
- When JavaScript waits for API responses or database queries before updating content, the delayed content insertion often triggers unexpected layout changes.
- Third-party scripts: Poorly implemented tracking pixels, chat widgets, social media buttons, and other external scripts contribute to CLS by loading unpredictably and inserting content without reserving space.
How to Measure CLS
Accurately measuring CLS is crucial for identifying problems and verifying fixes. Several tools provide different perspectives on your website's CLS performance:
PageSpeed Insights provides both lab and field data for CLS measurement. Lab data offers controlled testing conditions to identify specific issues, while field data reflects real-world user experiences over the past 28 days. The field data shows how your visitors experience layout shifts across different devices and network conditions. Access PageSpeed Insights athttps://pagespeed.web.dev/ and enter your URL for CLS analysis.
Lighthouse integrates into Chrome DevTools and provides detailed CLS auditing for individual pages. To get recommendations for reducing layout shifts, open Chrome DevTools (F12), navigate to the Lighthouse tab, and run a performance audit. Lighthouse is useful during development and testing phases because it provides actionable suggestions alongside your CLS score.
WebPageTest offers advanced performance testing with multiple configurations, including different locations, devices, and connection speeds. It provides filmstrip views and detailed waterfall charts to visualize layout shifts during page loading.
Chrome User Experience Report (CrUX) provides real-world CLS data from actual Chrome users who opted into usage statistics. This data represents genuine user experiences and should be your primary reference for understanding your website’s real-world performance.
When interpreting CLS scores, remember these thresholds: Good (≤ 0.1), Needs Improvement (0.1-0.25), and Poor (> 0.25). Focus on field data from CrUX and PageSpeed Insights, as it best represents your users' actual experiences with layout shifts.
Best Practices to Fix CLS
The most fundamental step in preventing layout shifts is specifying dimensions for images and videos. When browsers know an element's size before it loads, they can reserve the appropriate space, preventing content reflow.
<!-- Correct: Include width and height attributes -->
<img src="hero-image.jpg" width="800" height="600" alt="Hero image">
<!-- Correct: Using CSS aspect-ratio -->
<img src="hero-image.jpg" alt="Hero image" style="width: 100%; aspect-ratio: 4/3;">
Use the srcset attribute for responsive images alongside width and height attributes. Modern browsers automatically calculate the appropriate dimensions based on the specified aspect ratio:
<img src="small.jpg"
srcset="small.jpg 400w, medium.jpg 800w, large.jpg 1200w"
sizes="(max-width: 600px) 400px, (max-width: 1000px) 800px, 1200px"
width="800" height="600"
alt="Responsive image">
The CSS aspect-ratio property provides a modern approach to maintaining consistent dimensions while allowing flexible sizing based on container width.
Reserve Space for Ads, Embeds, and Iframes
Pre-allocating space for dynamic content prevents layout shifts when these elements load. Use placeholder containers that match the expected dimensions of your ads or embeds:
<!-- Reserve space for a standard banner ad -->
<div class="ad-container" style="width: 728px; height: 90px; background: #f0f0f0;">
<!-- Ad content loads here -->
</div>
Skeleton screens provide an elegant solution for maintaining visual stability while content loads. These placeholder elements give users a preview of the content structure and prevent jarring layout shifts.
Minimize Font-Related Layout Shifts
Using font-display: swap avoids FOIT by showing fallback fonts immediately while custom fonts load. However, overusing this property can lead to FOUT, where text changes from the fallback to the custom font, causing a brief flash of differently styled text.
@font-face \{
font-family: 'CustomFont';
src: url('custom-font.woff2') format('woff2');
font-display: swap;
\}
Preloading fonts reduces the delay between initial render and font availability:
<link rel="preload" href="critical-font.woff2" as="font" type="font/woff2" crossorigin>
Optimize for Dynamic Content Loading
Implement skeleton screens or placeholders to maintain visual stability while dynamic content loads. This technique is effective for user-generated content, product listings, or personalized recommendations.
Avoid inserting new content above existing content. If you must add content dynamically, consider using smooth CSS transitions to minimize the jarring effect.
Only update the DOM when all content is ready. Batching updates reduces layout recalculations and provides a smoother user experience.
Prioritize Resources
Use <link rel="preload"> to load important resources early in the page loading process:
<link rel="preload" as="image" href="hero-image.jpg">
<link rel="preload" href="critical-font.woff2" as="font" type="font/woff2" crossorigin>
Inline important CSS directly in your HTML head to reduce render-blocking and ensure essential styles are immediately available during initial page rendering.
Optimizing Images for CLS
Images often cause layout shifts because browsers need to calculate their dimensions on load. Without predefined dimensions, the browser initially allocates no space, then expands the layout when the image file arrives and its true dimensions are known.
Using width and height attributes in HTML gives the browser essential sizing information during the initial HTML parsing phase:
<!-- Proper image optimization for CLS -->
<img src="product-photo.jpg"
width="400"
height="300"
alt="Product description"
style="max-width: 100%; height: auto;">
These attributes should reflect your image file’s intrinsic dimensions. Modern browsers automatically maintain the correct aspect ratio, preventing distortion while preserving layout stability, even when CSS overrides one dimension.
The CSS aspect-ratio property provides a modern approach to maintaining consistent image proportions:
.responsive-image \{
width: 100%;
aspect-ratio: 4 / 3;
object-fit: cover;
\}
When using the srcset attribute for responsive images, always include width and height attributes based on your default image size. The browser uses these dimensions to calculate the space reservation, then provides the most suitable image from your srcset based on device characteristics and viewport size.
Managing Fonts and Css for CLS
Web fonts create layout shifts through two mechanisms: Flash of Invisible Text (FOIT) and Flash of Unstyled Text (FOUT). FOIT occurs when browsers hide text until custom fonts load, creating a jarring appearance when text suddenly appears. FOUT happens when fallback fonts initially appear, then get replaced by custom fonts, causing visible text reflow as character widths and line heights change.
The font-display property provides several strategies for managing font loading behavior:
/* Show fallback font immediately, then swap to custom font when available */
@font-face \{
font-family: 'HeadingFont';
src: url('heading-font.woff2') format('woff2');
font-display: swap;
\}
/* Optional: If it loads quickly, use custom font */
@font-face \{
font-family: 'BodyFont';
src: url('body-font.woff2') format('woff2');
font-display: optional;
\}
The swap value balances performance and visual consistency, while optional prevents layout shifts by using custom fonts that load within 100ms. Alternative values include block (brief invisible period, then swap) and fallback (brief invisible period, limited swap window).
Preloading fonts reduces the delay between page load and font availability:
<link rel="preload" href="critical-font.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="heading-font.woff2" as="font" type="font/woff2" crossorigin>
Choose font services that optimize delivery through subsetting, compression, and CDN distribution. Google Fonts, Adobe Fonts, and other professional services often outperform self-hosted fonts.
Handling Ads and Third-Party Content
Advertisements and embedded content cause layout shifts because they load asynchronously after the main page content. When an ad appears, it pushes existing content down or to the side, creating a significant and disruptive layout shift that frustrates users and harms conversion rates.
Effective ad management requires reserving space before ads load:
<!-- Reserve fixed space for banner advertisement -->
<div class="ad-placeholder" style="width: 728px; height: 90px; background: #f8f8f8; border: 1px solid #ddd;">
<div id="banner-ad-slot"></div>
</div>
<!-- Skeleton screen for content recommendation widget -->
<div class="widget-skeleton" style="width: 300px; height: 250px;">
<div class="skeleton-header" style="height: 20px; background: #e0e0e0; margin-bottom: 10px;"></div>
<div class="skeleton-content" style="height: 200px; background: #f0f0f0;"></div>
</div>
Whenever possible, request fixed-size advertisements from your ad networks. Variable-size ads make it impossible to reserve appropriate space, leading to inevitable layout shifts. Many ad platforms provide standardized sizes specifically designed to minimize CLS issues.
Third-party scripts require careful management to prevent performance issues:
<!-- Load non-critical third-party scripts asynchronously -->
<script async src="analytics-script.js"></script>
<script defer src="social-widgets.js"></script>
The async attribute allows scripts to load in parallel with HTML parsing, while defer ensures scripts execute after HTML parsing completes. Regularly monitor third-party script performance and remove or replace scripts causing layout shifts or slow page loading.
CLS Fixes for Dynamic Content
Dynamically injected content presents unique layout stability problems because it appears after the initial page render, often without proper space allocation. Common examples include notification banners, user-generated content feeds, personalized recommendations, and interactive widgets that load based on user behavior or external data.
Skeleton screens are the best solution for dynamic content loading:
<!-- Skeleton screen for dynamic content area -->
<div class="content-skeleton">
<div class="skeleton-line" style="height: 20px; background: #e0e0e0; margin-bottom: 10px; width: 80%;"></div>
<div class="skeleton-line" style="height: 20px; background: #e0e0e0; margin-bottom: 10px; width: 60%;"></div>
<div class="skeleton-line" style="height: 20px; background: #e0e0e0; width: 90%;"></div>
</div>
Avoid inserting content above existing content to prevent disruptive layout shifts. If you must add content above the fold, use smooth CSS transitions to minimize the visual impact.
Load and render dynamic content in hidden containers before inserting it into the visible DOM. This technique allows you to measure the content's dimensions and prepare appropriate space allocation:
// Load off-screen content, measure dimensions, then insert
const hiddenContainer = document.createElement('div');
[hiddenContainer.style](https://www.google.com/url?q=http://hiddencontainer.style&sa=D&source=editors&ust=1783631053971100&usg=AOvVaw3AVrCojxxFkpgdXDur1LCV).visibility = 'hidden';
hiddenContainer.innerHTML = dynamicContent;
document.body.appendChild(hiddenContainer);
const contentHeight = hiddenContainer.offsetHeight;
// Reserve space based on measured height before showing content
Testing and Monitoring CLS Fixes
After implementing CLS fixes, thorough testing ensures your optimizations work effectively across devices, network conditions, and user scenarios. Use PageSpeed Insights, Lighthouse, and WebPageTest to verify improvements in lab and real-world data.
PageSpeed Insights provides the most comprehensive view by combining lab testing with actual user data from the Chrome User Experience Report. You can compare your before-and-after scores, focusing on field data trends over time, as these reflect genuine user improvements.
Ongoing monitoring prevents CLS regressions and identifies new issues as your website evolves. The Chrome User Experience Report (CrUX) provides monthly data updates to track long-term trends in user experience metrics. Set up automated alerts through Google Search Console to notify you when Core Web Vitals scores decline.
Regular website audits should include CLS testing, especially after adding new features, updating themes, or integrating third-party services. Many performance monitoring tools offer continuous CLS tracking with alerts for significant score changes.
Integrate CLS testing into your CI/CD pipeline to catch layout shift issues before production. Tools like Lighthouse CI can automatically test performance metrics during development, preventing CLS regressions.
Relationship Between CLS and Core Web Vitals
CLS works alongside two other metrics in Google's Core Web Vitals. Largest Contentful Paint (LCP) measures loading performance, focusing on when the main content becomes visible, while Interaction to Next Paint (INP) measures interactivity, tracking the responsiveness of user interactions throughout the page lifecycle.
These three metrics provide a comprehensive view of user experience. A website might have excellent loading speed (good LCP) and responsive interactions (good INP), but if layout elements shift unexpectedly (poor CLS), the overall experience remains unsatisfactory. Conversely, stable layouts mean little if pages load slowly or respond sluggishly.
CLS is crucial because it affects user experience throughout the entire page lifecycle, not just during initial loading. While LCP and INP impact the first few seconds of a user's visit, layout shifts can occur at any time, disrupting interactions and creating lasting frustration that affects engagement, conversions, and brand perception.
Conclusion
Implementing an effective cumulative layout shift fix requires a comprehensive approach addressing images, fonts, dynamic content, and third-party elements. The strategies in this guide (specifying image dimensions, optimizing font loading, and managing dynamic content) work together to create stable, predictable user experiences that satisfy both visitors and search engines.
Success with CLS optimization comes from the consistent application of these techniques combined with ongoing monitoring and testing. Focus on measuring real-world performance through field data, as this most accurately reflects your users' actual experiences.
FAQ
Q: What is a good CLS score?
A good CLS score is 0.1 or less, indicating minimal unexpected layout movement during page loading. Scores between 0.1-0.25 need improvement, while scores above 0.25 are poor and require immediate attention.
Q: How often should I check my CLS score?
A: Monitor your CLS score monthly via the Chrome User Experience Report and run weekly tests using PageSpeed Insights or Lighthouse. Check CLS after significant website changes or new features.
Q: Is CLS more important on mobile or desktop?
A: CLS is important on both platforms, but mobile devices often experience more severe layout shift issues. This is due to smaller screens, variable network connections, and touch-based interactions that make accidental taps more problematic when elements shift unexpectedly.
Q: Can CLS affect my website's accessibility?
A: Yes, excessive layout shifts create significant accessibility barriers for users with disabilities, particularly those using screen readers, keyboard navigation, or assistive technologies that rely on consistent page structure and predictable element positioning.
Ready to put this into practice?
Growth Limit runs full-stack organic for one client per industry.