#Core Web Vitals#CLS

What is Cumulative Layout Shift (CLS), and how can we optimise it?

Sander Heilbron
by Sander Heilbron
iron-out-blog-cumulative-layout-shift

Have you ever visited a website where a text, image or button suddenly moves while loading? Or even after loading? Imagine you’re trying to click on a payment button but you’re ending up emptying the whole shopping cart. Bad for you... but even worse for that webshop because the chance you’ll try again is pretty low, right? Sudden layout shifts are annoying for the user and can even cause real commercial damage. In this article, we will discuss how you can optimise your website for the Google Core Web Vitals metric, Cumulative Layout Shift (CLS).

What is a layout shift #

The Cumulative Layout Shift is a Google Core Web Vitals metric to assess the visual stability of your website. To be more precise: it is a measure of the largest burst of layout shift scores (session window) for every unexpected layout shift that occurs during the entire lifespan of the page (measured while loading and while interacting with the page).

It is one or a series of layout shifts that occur with less than 1-second of each other within a session window with a total duration of up to 5 seconds for the total window duration. The largest burst is the session window with the maximum cumulative score of all layout shifts within that window.

Together with the other two Core Web Vitals ‘Largest Contentful Paint’ and ‘First Input Delay’ they assess several aspects of user experience: loading speed, responsiveness and visual stability. The results of this assessment are used as signals of page experience used by Google's core ranking systems for Google Search. If you score ‘good’ on all three Core Web Vitals you can gain better ranking positions.

But let’s go back to CLS and look at two examples of a shifting layout. It’s pretty annoying right...?

Unexpected layout shifts can cause significant issues for users. This user's intention was the opposite of what actually happened on the page.

But it can also be somewhat less severe in appearance, but certainly no less annoying. A common problem which causes users of your site to have to search again for the position of the text they were reading.

Like with the other Core Web Vitals that are more speed related, the visual stability can influence the user experience of the page heavily. However, in contrast to speed, visual stability can’t be measured or expressed in time. Therefore Google invented a layout shift score which is a product of two different elements which we will explain next.

How CLS score is calculated for measuring visual stability #

To calculate the layout shift score, the browser looks at the total size of the viewport and the movement of so-called unstable elements in the viewport between two rendered frames. With rendering we mean the process that turns website code into the interactive pages users see when they visit a website. The layout score is a product of measures of the movement: the impact and the distance fraction.

The impact fraction measures how unstable elements impact the viewport area between two frames.

In the image above we have an element that fills half the viewport in one frame. In the next frame this element shifts by 25% from the viewport height. The red dotted rectangle represents the visible area of the element in both frames, in this case 75% of the total viewing window, so the impact fraction is 0.75.

The distance fraction measures the distance that these unstable elements have moved in relation to the viewport.

In the image above, the largest viewport dimension is the height. The unstable element has moved 25% of the viewport height, making the distance fraction 0.25.

So in this example, the impact fraction is 0.75 and the distance fraction is 0.25, so the layout shift score is 0.75 * 0.25 = 0.1875.

What is a good CLS score? #

In order to provide a good user experience your website should aim for a cumulative layout shift score of 0.1 or less. Like with the other Core Web Vitals Google uses a 75th percentile of page loads segmented across mobile and desktop browsers. In other words: 75% of your users should experience a CLS score of 0.1 or less in order to pass Core Web Vitals assessment. Between 0.1 and 0.25 you will need improvements and above 0.25 you’ll get a poor score, which means you don’t pass the Core Web Vitals. Remember: in order to pass the Core Web Vitals assessment you need to score good on all three metrics FID, LCP and CLS.

Measuring in the field vs. measuring in the lab #

There are two methods to measure website performance: gathering data in the field and in the lab. CLS can be measured both in the field and in a lab setting.

In the lab we can only measure experiences of a potential user. In the lab, we cannot initiate interactions, possible layout shifts can only be measured during the initial page load (initial-load CLS issues). In addition, measuring in the lab has several other shortcomings compared to measurements in the field. A lab environment might be unreliable because certain functionalities are switched off or work differently. Some examples are: cookie banners, live chat tools, ads or personalised content. When you observe CLS issues in the lab, you can assume that real users will also experience them. So you need to resolve these before going live.

If you really want to steer based on reliable data you should look at field measurements. With ‘the field’ we mean real life users, people on the internet who interact with your site. In the field CLS is measured throughout the full life of the page, both 'initial-load CLS' and 'post-load CLS' issues are measured in the field. When the field and lab CLS scores are not in line, then this likely indicates post-load CLS issues.

Not all layout shifts are bad #

User-initiated layout shifts #

A layout shift is only bad when the user is not expecting it. However, when there is a layout shift immediately after a user interacts with a page (via a click, tap or keystroke) then this is not a problem. At least not if the time between the interaction and when the layout shift takes place are not too far apart (it should make sense to the user that the layout shift occurs as a result of his or her interaction). Layout shifts that occur within 500 milliseconds of user input (scrolls, drags, pinch and zooms are excluded)) will have the hadRecentInput flag set, so they can be excluded from calculations.

Animations and transitions #

Animations and transitions make it possible to update content on pages. They make it clear to users what is happening and steer them between different states. When done properly - smoothly without abrupt movements (shifts) - this provides a good experience.

When using animations or transitions, movements between different positions will have to occur naturally to provide a good experience. CSS transform property allows you to animate elements without triggering layout shifts:

  • Use transform:scale() instead of changing width and height properties.
  • For repositioning elements, use transform:translate() instead of modifying top, bottom, right and left properties.

Common causes of Cumulative Layout Shift (CLS) #

So...layout shifts can distract or dissatisfy users, or even send them away if the functionality of a certain element or page is heavily affected. Therefore it’s recommended to take action if your website has a CLS score above 0.1.

The most common causes of too much layout shifts are:

  • Images without predefined dimensions.
  • Ads, embeds, and iframes without dimensions.
  • Dynamically loaded content (injected via client-side JavaScript) such as ads, embeds, and iframes without dimensions.
  • Custom web fonts causing flashes of unstyled text (FOUT) due to a visual difference with to the fallback (system) font.
  • Tasks waiting for a network response before updating DOM (asynchronous requests).
  • Post-load shifts that are unexpected by the user may be included where there was no qualifying interaction:
    • Interactions or transitions (inside Single Page Apps), which take longer than the 500 millisecond grace period.
    • Lazy loaded content causing shifts during page scrolling. *
    • Content shifting on hover. *

* Both scroll and hover are ineligible for the 500 milliseconds grace period as CLS during these periods are seen as being "unexpected shifts"

Layout shifts can be caused by the following events:

  • Changes to the position of a DOM element
    • In particular, the DOM element immediately preceding the shifted element is the element most likely to be involved in "causing" the layout shift.
  • Changes to the position of an element that aren't due to the movement of another element
    • Stylesheets that are loaded late or overwrite previously declared styles.
    • Animation and transition effects.
  • Changes to the dimensions of a DOM element
    • Stylesheets that are loaded late or overwrite previously declared styles.
    • Images and iframes without width and height attributes that load after their "slot" has been rendered.
    • Text blocks without width or height attributes that swap fonts after the text has been rendered.
  • Insertion or removal of a DOM element
    • Insertion of ads and other third-party embeds.
    • Insertion of banners, alerts, and modals.
    • Infinite scroll and other UX patterns that load additional content above existing content.
  • Animations that trigger layout
    • Repositioning elements by incrementing properties like top or left

Tips to improve your Cumulative Layout Shift (CLS) score and user experience #

Some tips for improving the CLS:

  • Include width and height attributes for all images and videos. Or at least one of these dimensions in combination with an CSS aspect-ratio.
  • Preload font files for key fonts and download as priority assets.
  • Ensure the appropriate fallback font is used.
  • Minimize the size differences between the fallback font and the web font using the new size-adjustascent-overridedescent-override, and line-gap-override APIs.
  • Never load dynamic content without a user interaction above content that’s already loaded. Alternatively, ensure the element is not part of the document flow by overlaying the content where this makes sense.
  • Use a placeholder or fallback for your embeds.
  • Reserve space and show a loading indicator for asynchronous loaded resources (as well when the content is likely to take more than 500 milliseconds following user input)
  • Avoid placing late-loading content near the top of the viewport
  • Have the user initiate the load of new content, so they are not surprised by the shift (for example with a "Load more" or "Refresh" button).
  • transform animations can be used to translate, scale, rotate, or skew without triggering a re-layout and so completely avoiding layout shifts
  • Reduce CLS by ensuring pages are eligible for the bfcache (back/forward cache)

If you really want to dig a little deeper you should read the article of Addy Osmani about optimising CLS on Web.Dev.

Tools for measuring Cumulative Layout Shift (CLS) on your website #

There are various tools to help business owners gain a better understanding of their CLS score based on field data. The first two are considered to provide “actual measurements” of a site based on real user (field) data:

The next two provide users with CLS scores calculated from lab data:

Conclusion about Cumulative Layout Shifts #

The Cumulative Layout Shift undoubtedly deserves to be one of the three Core Web Vitals. Next to loading speed and interactivity, it’s at least annoying to have a webpage that is visually unstable with images, videos or buttons flying around over your screen.

If you want to improve visual unstable elements, you should focus on setting fixed image or video sizes, watch out with the loading order of dynamically injected content, preload fonts and use placeholders or fallbacks for embeds. We totally get that this might sound a bit too technical so we can always help you to assess and improve your CLS performance.

On our homepage you can find a simplified version of the assessment tool from Google where you can check if you pass Google’s Core Web Vitals test.

Continue reading

Get more business out of your website

The performance of your website needs improvement.

You can get more business by creating happy customers by giving them a good user experience. Start now and request a performance audit.