It is called Cumulative Layout Shift, and it is one of the three Core Web Vitals that will be ranking factor on Google from 2021, as announced in early June: it is therefore an element with which to deal in order to have a performing site and ensure a positive user experience,by complying with the indications and desires of the search engine. So letâ€™s take a closer look at this metric, to better understand what it is, how it is measured and how we can optimize it.
What is the CLS, Cumulative Layout Shift
Cumulative Layout Shift (CLS) is a metric of Google that measures visual stability through the analysis of an event of the user experience, or the unexpected shift of the elements of the web page while the same is still being uploaded.
Unlike the other two Core Web Vitals – Largest Contentful Paint and First Input Delay – its reference unit is not time, but space, and Google has created a specific score to identify the level of layout variations during page loading, which can compromise the user experience.
The issues with the layout variations
The CLS occurs when the content of the page moves without the userâ€™s voluntary input or prior notification: the onpage elements that tend to cause variations are characters, images, videos, contact forms, buttons and other types of content.
In the most common case, the user who is visiting the page is ready to click on an element, but in the meantime the loading modifies the position and leads the person to “make a mistake” and click on something else, often even an ad or a pop-up window.
Examples of errors with CLS
To better understand what the Cumulative Layout Shift is – and how annoying it can be – just watch this short explanatory Google video.
As you notice, the user wants to click the button to vary the order, but the sudden and unexpected appearance of a pop-up modifies the layout of the page and moves the items lower than the previous position. So, the tap that would first end up on the “no” actually lands on the confirmation of the cart, causing a frustration (and probably also quite a lot of nuisances and irritation).
Another type of problem may occur when reading an article: instead of allowing the operation to be completed without interruption, the text or other elements change and the user loses the visual reference of his reading, having to shake the page to find the paragraph he was actually at.
The importance of Cumulative Layout Shift for SEO and UX
“Most of the time these types of experiences are just annoying, but in some cases they can cause real damage”, write Philip Walton and Milica Mihajlija on web.dev, adding that “a low CLS helps to ensure that the page is enjoyable” for users.
Minimizing this parameter is therefore important because moving pages can cause a poor user experience, and the problem is even greater on mobile devices, because smartphone screens are smaller and the impact of variations is more intense.
A poor CLS score is indicative of coding problems that can be solved.
Causes of the CLS
According to the Googlers there are five reasons why a cumulative variation of the layout occurs:
- Pictures or videos of unknown size / not set correctly.
- Ads, embeds and iframes without dimensions.
- Injected content
- Web fonts that cause FOIT / FOUT
- Actions waiting for a network response before updating DOM
Thus, unexpected shifts may occur “because resources are loaded asynchronously or DOM elements are dynamically added to the page above the existing content“, but they may also be responsible for “an image or video with unknown size, a character that becomes larger or smaller than its fallback or a third-party ad or widget that dynamically resize itself”.
What makes these factors even more problematic is that the way a site works in development is “often quite different from how users experience it”: for example, personalised or third-party content may not behave in the same way in development as in production, test images are usually already in the developer browser cache and the API calls that are run locally are sometimes so fast that the delay is not blatant.
What the CLS measures
The CLS metric “measures the total sum of all scores of individual layout shifts for each unexpected layout shift that occurs during the entire length of the page”: a change in layout occurs whenever a visible item changes its position from one frame to the next.
To provide a good user experience, sites should try to have a CLS score of less than 0.1 and “to be sure to achieve this goal for most of your users, a good threshold to measure is the 75th percentile of page loads, segmented on mobile and desktop devices”.
Layout variations are defined by the Layout Instability API, which reports layout-shift entries whenever an element visible with the viewport changes its initial position between two frames; these elements are considered unstable.
How Google calculates the Cumulative Layout Shift score
To calculate the score of layout variation, the browser examines the size of the window and the movement of unstable elements in the window between two rendered frames.
In practical terms, the CLS score is the product of two measures of that movement: impact fraction and distance fraction, translatable as a fraction of impact and fraction of distance, which take into consideration the percentage of the browser screen affected by the layout changes.
What is the impact fraction
The first parameter measures the impact of unstable elements on the area of the window between two frames and then takes into account the area of the browser screen affected by changes in the layout.
The fraction of impact for the current frame is given by the merging of the visible areas of all unstable elements for the previous frame and for the current one, as a portion of the total area of the window.
The image helps to better understand: an element occupies half of the window in a frame; in the next one, the element moves down 25% of the window height. The red and dashed rectangle indicates the union of the visible area of the element in both frames which, in this case, is 75% of the total view, so its impact fraction is 0.75.
We can say that the fraction of impact measures the total space that the element of a window has occupied, from the position it has in the view when it is displayed for the first time up to the final one, at the end of the rendering of the page.
What is the distance fraction
The other part of the CLS scoring equation measures the distance vertically and/or horizontally that unstable elements have travelled in relation to the window; is calculated by dividing the longest distance travelled by an unstable element moved in the box by the largest size of the window (width or height).
Again, the visual example helps to better understand the value: the larger window size is the height and the unstable element has shifted by 25% of the window height, which makes the fraction of distance 0.25.
Initially, the CLS only considered the impact fraction, but then Google decided to introduce this second factor to avoid excessively penalizing cases in which large items move by a small portion.
The definitive score of the CLS
In the given example, then, the overall layout variation score is 0.75 * 0.25 = 0.1875, given by multiplying the number of impact fractions (0.75) and that of the distance fraction (0.25). As said, for Google a CLS score is considered good when it is less than 0.1
Examples of layout variation
The in-depth analysis of wev.dev shows with other examples such as the adding of content to an existing element affects the score of the layout variaton.
In this case, the “Click Me!” button is added at the bottom of the gray box with black text, which pushes the green box with white text down (and partially out of the view box).
Even if the gray box changes in size, its initial position does not change and therefore is not considered an unstable element. On the other hand, the button was not previously in the DOM and thus does not even change its initial position.
To change is the initial position of the green box: as it has been partially moved out of the viewport, the invisible area is not considered in the calculation of the impact fraction. This means that the union of the areas visible for the green box in both frames (illustrated by the red and dotted rectangle) is equal to the area of the green box in the first frame, that is 50% of the window. So the impact fraction in this case is 0.5.
The distance fraction is illustrated with the purple arrow: the green box has moved down about 14% of the window, so the distance fraction is 0.14.
The score for layout variation is therefore 0.5 x 0.14 = 0.07.
Adding other non-fixed elements makes the situation even more complicated. In the first frame above there are four results of an API request for animals, sorted in alphabetical order; in the second, more results are added to the ordered list.
The first element of the list (“Cat”) is stable and does not change its initial position; the new elements added to the list were not previously in the DOM, so even their initial positions do not change, but the objects labeled “Dog”, “Horse” and “Zebra” change their starting position and are therefore unstable.
The red and dotted rectangles in the image represent the union of these three unstable areas before and after, which in this case cover about 38% of the window area (and impact fraction of 0.38). The arrows represent the distances that unstable elements have travelled from their initial positions. The “Zebra” element, represented by the blue arrow, is the one that has moved the most (about 30% of the window height) with the fraction of distance in this example of 0.3.
The score for layout variation is 0.38 x 0.3 = 0.1172.
Expected and unexpected layout variations
Not all layout shifts are negative, point out in the article Philip Walton and Milica Mihajlija, and many dynamic web applications often change the initial position of the elements on the page.
Only unexpected layout changes are wrong and problematic for the user, while generally good are changes that occur in response to user interactions (clicking on a link, pressing a button, typing in a search box, etc.), as long as the move is done quickly and consequentially to the interaction, making clear the cause-effect relationship for the user.
If not – if, for instance, a user interaction triggers a network request that may take some time to complete – it would be better to immediately create some space and show an upload indicator to avoid an unpleasant shift of the layout to completion of the request. If the user does not realize that something is loading or has no idea when the resource will be ready, he might try clicking on something else while waiting, something that might then move to the end of the first action started.
According to the Googlers, animations and transitions – if well executed – “are a great way to update the page content without surprising the user”: the content that moves suddenly and unexpectedly on the page almost always creates a bad experience for the user, but content that moves gradually and naturally from one location to another can instead help the user to better understand what is going on and guide him through status changes.
How to measure the site’s Cumulative Layout Shift: field tools and lab tests
We now come to some practical and useful information to verify the performance of our site and our pages: the CLS can be both measured in-lab or on the field and is available in various tools.
Among the lab tools, instead, we have Chrome Devtools, Lighthouse and Webpagetest. These lab tests simulate the behavior of the site when a real user downloads a Web page: Google uses a Moto G4 smartphone to generate the CLS score within the lab environment.
But we must remember that lab tools – which are ideal to understand how a layout can be executed before sending it to users and offer publishers the opportunity to test a layout to find out any problems in advance – typically load pages into a synthetic environment and thus are only able to measure changes in layout that occur during page loading. As a result, the CLS values for a given page reported by such tools may be lower than those experienced by real users in the field.
How to optimize and improve the CLS
For most websites, you can avoid all unforeseen layout changes by following certain guiding principles, such as:
- Always include size attributes on images and video elements, or reserve the required space with something like CSS boxes.
This approach ensures that the browser can allocate the correct amount of space in the document when uploading the image.
Moreover, it is also possible to use unsized-media feature policy to force this behavior in browsers that support feature policies.
- Never place contents above existing ones, except in response to a user interaction. This ensures that any layout changes are expected.
- Prioritize the transformation of animations into property animations that activate layout changes. Animating transitions will provide context and continuity from one state to another.