Chapter 3:

Cumulative Layout Shift

October 5, 2021
10 min read

Cumulative Layout Shift (CLS)

Delivering valuable, keyword-focused content with high engagement isn’t enough to guarantee a top spot in search results.  For websites to be successful on the web, they must also maintain high-quality user experiences. But what does a high-quality user experience look like? To answer that question, we look to Google’s guidelines on the matter. 

Among those guidelines, the most critical are known collectively as Core Web Vitals. Read our article devoted to explaining Core Web Vital if you are not already familiar. This article focuses on one Core Web Vital in particular, Cumulative Layout Shift, and how you can optimize your site’s visual stability to obtain a better score.

What is Cumulative Layout Shift?

Cumulative Layout Shift (CLS) is a score that determines visual stability based on a specific algorithm. We have devoted a section of this article to explain the algorithm used for calculating the CLS score. 

You need to maintain your CLS score below 0.1 to ensure a good user experience. The lower your score, the more stable your page layout. Scores higher than 0.1 mean that you don’t get any search engine ranking benefits from the performance of your page, which allows competing pages with higher performance to rank higher. 

According to Chrome UX report, as of June 1st 2021, 62.2% of websites delivered a CLS score of less than 0.1 for desktop experiences (61.5% for mobile). However, only 40.2% of websites received an overall passing score for all core web vitals. That number drops to 28.3% for mobile experiences.  

The Importance of Visual Stability

Imagine you are shopping from your phone and have a few shirts in your cart. You decide you want to update the quantity of the shirts you’ve selected and proceed to navigate to your cart view. Upon selecting edit, the page layout shifts, and your thumb selects “remove item” instead of “+1.” This experience is frustrating for the user caused by visual instability

While there’s no significant risk to the user in our shopping example, you can imagine extreme scenarios where visual instability could lead to worse outcomes: accidentally submitting an incomplete form, inputting the wrong amounts, checking out before updating your shipping information, and so on. For these reasons, Google considers Visual Stability to be one of the most important metrics for any given web page. 

This is especially true when you consider that most web experiences have been created for desktop viewing, and yet 50% of internet traffic is mobile. That means half of your users could potentially be exposed to unpleasant layout shifts if the page is not designed with mobile visual stability in mind. 

To measure Visual Stability, Google uses the Cumulative Layout Shift (CLS) metric.

Case Study: The Cumulative Layout Shift Business Impact

The Telegraph Media Group limited (TMG) operates one of the oldest newspapers in England by the name of the Daily Telegraph founded in 1855. They also operate a news website that attracts an estimated 28 million unique visitors each month. 

TMG’s web administration team was one of the first to recognize the impact of core web vitals on their revenue that relies on selling digital advertising. Their improvement efforts led to the creation of a case study promoted by Google. The improvement in core web vitals impacts their sales in two ways:

  • It improves the ranking of news articles on the Google search results pages due to Google increasing the core web vital signal in the search algorithm starting in June of 2021. The improvement in ranking results in more organic traffic to their website that drives advertising sales.

  • It improves the on-page user experience that keeps the visitors longer on their website enjoying the content. As much as selling ads is important, loyal Telegraph readers return for a strong editorial and a polished presentation of the content. 

Ironically, the presence of the same revenue-generating ads caused a layout shift. They resolved the CLS problem by standardizing the ad sizes (height and width) and reserving space for the advert slot that matched the common ad sizes. The images below show the difference before and after.

Before the improvement:

After the improvement:

They also improved how images, headers, and embeds (such as YouTube videos) were loaded on their pages by following instructions similar to those provided later in this article. As a result, their website’s CLS score improved by 250%, driving more visitors to their website who spent more time reading the news and clicking on ads.

How do you calculate a Cumulative Layout Shift score?

The scoring algorithm calculates CLS by slicing a page’s loading time into windows of time and selecting the window with the highest CLS score. Let’s start by defining the windowing concept in more detail.

  • Session Window: A window triggered by an unexpected layout shift that closes after 1 second of no additional layout shifts, with a cap of 5 seconds. 
  • Layout Shift Scores: A calculation for each layout shift occurring within the 5-second session window. 
  • Layout Shift: Whenever an element moves to change its position from one frame to the next.  

Once you have determined the time windows, use the following metrics for each layout shift that occurred in that session window:

  1. Impact Fraction:  The geometric union of all shifting nodes in the frame as a percentage (Impact Region), divided by the total viewport.
  2. Distance Fraction: Represents the greatest node-shift distance in a frame, divided by the viewport’s width or height (whichever is greater). 

Let’s say an element takes up 60% of the total viewport and then shifts by half of its eight. Here’s what that means:

  • The Impact Region of the viewport is 90% (60% + 30%)
  • The Impact Fraction is 0.9 (90% of 1 view port’s height)
  • The Distance Fraction is 0.3 (30% of view port’s height ) 

Now, multiply these scores to get a layout shift score.   

0.9 x 0.3 = 0.27

You must score every layout shift in a session window. After you have calculated each layout shift’s score, add the scores together. For simplicity, let’s say our page only had one layout shift occur. The CLS would then be 0.27. 

Note: Even if a separate session window has a sum of 0.20 CLS, it will not impact your CLS score. Google only measures the maximum session window. As a reminder, session windows can last up to 5 seconds and close after 1 second of no additional layout shifts. 

For a deep dive into this topic, check out this article

What is considered a good CLS score?

You should aim for a CLS score below 0.1 to provide the most optimal user experience. Any score above 0.25 is categorized as a bad score and typically means your users are negatively impacted. We explain how to measure a page’s CLS score iIn the next section of this article. You can click on the hyperlink underneath each screenshot to see more information. 

A Low CLS Score (0.001)

Result of smartblogger.com 

A High CLS Score (0.571)

Result of ahcustom.com 

How to detect Cumulative Layout Shift issues?

You can measure CLS in two ways: 

  1. Via Synthetic Monitoring:  Uses a combination of agents (for data collection) and synthetic tests (for user activity simulation) to gather performance information, including CLS metrics. 
  2. Via Real User Monitoring (RUM): Uses actual, real-user experiences as the data that’s collected. This data reflects the entire lifespan of the page. 

To get you started quickly, simply follow these steps to run a synthetic test: 

  1. Go to https://www.webpagetest.org/webvitals  
  2. Input your URL and select a test configuration. After a couple of minutes, your test should be ready for review.
  3. Scroll down to Cumulative Layout Shift to see more detail about your CLS score.
  4. Hover over each image to visualize the layout shifts (the animation triggers upon hover). 

A key differentiation provided by WebPageTest is that you can also view the entire test as a frame-by-frame filmstrip or a video. Simply select “View as Filmstrip” or “View Video” on the hyperlinks presented at the bottom of the screenshot showing the results from the New York Magazine’s homepage

The filmstrip shows each frame during the page’s loading and automatically highlights the frames where the core web vital problems appear (click here to see example): 

The video is a timed recording of what a user sees on a mobile phone while the page loads as presented below (click here to see example):

Advanced Cumulative Layout Shift Measuring

JavaScript APIs

The Performance Observer API is one way you can obtain RUM web performance data from real-world users. It looks for performance-related events on a web page and notifies you about the new performance entries recorded in the performance timeline of your browser. By creating a new PerformanceObserver, you can identify a specific event during your website’s visitors’ session. You can programmatically get the information about the sources causing CLS.

 

let cls = 0;

new PerformanceObserver((entryList) => {

  for (const entry of entryList.getEntries()) {

    // 500 ms input exclusion window

    if (!entry.hadRecentInput) {

      cls += entry.value;

      console.log('Current CLS value:', cls, entry);

    }

  }

// the buffered flag enables observer to access entries from before the observer creation

}).observe({type: 'layout-shift', buffered: true});

 

Web-Vitals Library

You can use this library to determine the Core Web Vitals score using RUM data.  A more refined analysis can be made for debugging purposes. For instance, you can set the second argument in the getCLS function to true if you want to report each layout shift:

 

import {getCLS} from 'web-vitals';    

// Logs CLS as the value changes.
getCLS(console.log, true);

 

Top Causes of Cumulative Layout Shift and How to Solve Them

There are three main causes of CLS. In the following sections, we’ll take a look at each in addition to how to resolve each issue. You can follow along using your WebPageTest results. Review each session or filmstrip’s highlights to determine which kind of issue you are dealing with.

  1. No Dimensions Defined for Media

Problem

When height and width dimensions are not specified on media such as images and video, the media content is forced to push any accompanying text down or beyond the viewport. This happens because text loads much faster than media on a web page, and without placeholders provided to guide how the text is laid out, the page must adjust as more content loads. 

A visual explanation of the impact of defining media dimensions (source).

Example

To isolate the problem, create a film strip using WebPageTest that automatically highlights the frame with a layout shift in the loading process. 

For example, see the frame at 14.5 seconds in the screenshot below (highlighted with a dotted yellow line) taken from the main page of the Washington Post website showing a layout shift in the top section of the frame. In this case, the creation of the space required to load the image (seen after 17 seconds) caused the shift. You can click here to see an archived copy of the result shown below since the Washington Post homepage will most certainly change by the time you read this article.


Solution: Add Size Attributes

This resolution is fairly simple: simply add width and height attributes to all of your images, like so:

  2. No Space Allocated for Slow-Loading and Dynamic Content

Problem

If space is not properly reserved for elements like ads, embeds, iframes, and dynamically injected content, layout shifting can occur. You can mitigate this by ensuring the container or ancestor elements have dimensions that already provide enough space on first render. 

Example

WebPageTest is also able to create a video recording of the loading experience from the perspective of a potential end user on the specified device/browser type. To quickly share it, simply save it as a .gif.  

For example, you can see how the following ads on theverge.com website cause several layout shifts at 1.5s, 4s, 5s, 7.5s, and so on. In this case, the slow-loading content isn’t fully displayed until 17s. You can click here to see an archived copy of the result shown below since the content of the page will have changed by the time you read this article.

Solution: Reserve Space for Content

Reserve the space for slow-loading and injected content using placeholders of specified width and height.  Here are a few examples of specifying the adverts dimensions in CSS and JS.

 

<div class="ads" style="min-width: 300px; min-height: 250px;"></div>

 

Reserving space (image on the right) avoids shifting of content (source).

  3.  Suboptimal Web Fonts

Problem

Web fonts are popular, but when not optimized they can cause layout shifts in two ways: 

  1. FOUT (Flash Of Unstyled Text): Occurs when a page displays text using the default fallback font before the desired font style is rendered, causing dimensional re-arrangements due to varying font width and height. 
  2. FOIT (Flash Of Invisible Text): Occurs when an ‘invisible’ font is displayed while the web page is waiting for the primary font style to render. 

Example

Depending on your page layout, web fonts can have a dramatic impact on your CLS score. Taken from bbc.com/news, you can see how just a flash of unstyled text can dramatically impact your score. At 2s into page load, the text’s styling loads, changing how many news cards fit on each row (notice the extra card on the right side of the top row), and affecting the CLS score by a massive 0.489. Remember, a score of 0.1 is what you are aiming for. You can click here to see an archived copy of the result shown below. This archived version helps you see the firm strip given the content of the page will have paged by the time you read this article.

Solution: Prepare a Text Rendering Strategy

To avoid font-induced layout shifts, you can define a text rendering strategy using the CSS descriptor font-display. For example, you can set the font-display to optional within an at-rule. If your primary font fails loading in the first 100ms, the text is simply rendered using the fallback font. 

You can also combine font-display: optional with <link rel="preload"> to preload optional fonts to completely eliminate layout shifts.

Headline web font loading causes a layout shift. View test on this archived version of WebPageTest’s film strip since the content on the BBC web page will have changed by the time you read this article.

Source

Summing Up

As you’ve learned, the Cumulative Layout Shift (CLS) metric is a user-centric metric that plays a critical role in your web page's search rankings. CLS measures the visual stability of a given page, calculated by taking the maximum session window’s total layout shift scores. 

Understanding, debugging, and improving CLS is an excellent step towards targeted page optimization, especially when combined with other user-centric web performance metrics. A good CLS score enhances your user experience, boosts SEO, and increases leads, conversions, and revenue.