Cumulative layout displacement (CLS) is an important user-centric metric for user visual stability because it helps quantify how often a page’s layout changes when a user opens it. Currently, the official recommendation is that this metric should be less than 0.1, and such CLS will help ensure the user experience of the page.
Imagine a scenario where you want to click on a link or a button, but at the moment your finger drops (BOOM), the link moves and you end up clicking on something else! Isn’t that a terrible experience? Here’s an example:
Page layout changes are usually caused by asynchronously loading resources or dynamically adding DOM elements to a page above existing content. The culprit could be an image or video of unknown size, or a third-party AD or widget that dynamically resizes itself.
The difficulty in solving this problem is that the functionality of the site under development is often very different from the user experience. Personalization or third-party content behaves differently in the development environment than it does in production. Resources such as images at development time usually already exist in the developer’s browser cache, and local API calls are usually quick, so latency is not noticeable.
The cumulative layout displacement (CLS) metric helps you find these problems by measuring how often actual users change.
What is CLS?
CLS is the sum of scores that measure layout changes for each element that occur over the life of a page.
Layout movement is defined by the Layout Instability API, which defines that elements visible in the viewport are considered unstable when they change their starting position between two render frames.
Note that layout movement occurs only when an existing element changes its starting position. If a new element is added to the DOM or an existing element changes size, that element does not count as a layout offset as long as the change does not cause other visible elements to change their starting position.
What is a good CLS score?
In order to provide a good user experience, websites should strive to keep the CLS score below 0.1. To ensure that the majority of users achieve this goal, the basic standard for mobile and desktop devices is that 75% of the page score meets the requirements.
For more information on the research and methodology behind this recommendation, see: Defining the Core Web Vitals(web.dev/defining-co…
Influence score
To calculate the layout change score, the browser looks at the viewport size and the movement of unstable elements in the viewport between two render frames. The layout offset score is the product of two measures of the motion: the impact score and the distance score.
layout shift score = impact fraction * distance fraction
Copy the code
Impact score
The impact score measures the impact of a variable element on a page’s viewport between two render frames. The union of the visible regions of all unstable elements from the previous frame and the current frame (as part of the total viewport area) is the influence fraction of the current frame. / / figure
In the figure above, one element occupies half of the viewport in one frame. Then, in the next frame, the element moves down 25% of the viewport height. The red dotted rectangle represents the union of the visible areas of the elements in the two frames, which in this case is 75% of the total viewport, so its influence score is 0.75.
Distance fraction The distance fraction is the maximum distance (horizontal or vertical) that an unstable element can move in the viewport divided by the maximum size (width or height, whichever is larger) of the viewport. In the example above, the maximum viewport size is height, and the unstable element moves 25% of the viewport height, giving a distance fraction of 0.25.
So, in this example, the influence score is 0.75 and the distance score is 0.25, so the layout shift score is 0.75 * 0.25 = 0.1875.
How does adding content to an existing element affect layout shift scores
// Click Me! The button is added to the bottom of the gray box with black text, which pushes the green box with white text down (and partially out of the viewport).
In this example, the gray box has changed size, but its starting position has not changed, so it is not an unstable element. The button was not in the DOM before, so its starting position does not change.
However, the starting position of the green square does change, but since it has been partially moved out of the viewport, the invisible area is not taken into account when calculating the impact score. The combination of the visible area of the green box (represented by a red dotted rectangle) in both frames is the same as the area of the green box in the 50% viewport in the first frame. The impact score is 0.5.
The distance fraction is represented by a purple arrow. The green box has moved down about 14% of the viewport, so the distance score is 0.14.
The layout displacement score is 0.5 x 0.14 = 0.07.
Multiple unstable elements
In the first frame above, there are four results of an API request for an animal, sorted alphabetically. In frame 2, more results are added to the sorted list.
The first item in the list (“Cat”) does not change its starting position from frame to frame, so it is stable. Similarly, new items added to the list were not previously in the DOM, so their starting position does not change. But items labeled “dog,” “horse,” and “zebra” all changed their starting positions, making them unstable elements.
The red dotted rectangle again represents the combination of the front and back regions of the three unstable elements, in this case approximately 38% of the viewport region (impact rate 0.38).
The arrow shows how far the unstable element has moved from its starting position. The “zebra” element represented by the blue arrow moved the most, moving about 30% of the viewport height. The distance score in this example is 0.3.
The layout displacement fraction is 0.38 x 0.3 = 0.1172.
Expected vs. unexpected layout changes
Not all layout changes are bad. In fact, many dynamic Web applications often change the starting position of elements on a page.
A layout change is only bad if the user doesn’t expect it. In addition, layout changes that occur in response to user interactions (clicking a link, pressing a button, entering a search box, etc.) are generally good, as long as the changes occur close enough to the interaction that the user can clearly see the relationship.
Animations and transitions are great ways to update page content without taking users by surprise. Sudden movement of content on the page almost always leads to a poor user experience. However, content that gradually and naturally moves from one location to another can often help users better understand what’s going on.
The CSS transform property allows you to animate elements without triggering layout shifts, such as using transform: scale() instead of changing the height and width properties. To move elements, avoid changing the top, right, bottom, or left attributes and use transform: Translate () instead.
How do YOU measure CLS
1. CLS can be detected with Lighthouse and Performce. // Figure 2. Manual measurements can be made using the layout instability API. Create a PerformanceObserver that listens for unexpected layout movement elements, adds them up, and logs them to the console.
let cls = 0;
new PerformanceObserver((entryList) = > {
for (const entry of entryList.getEntries()) {
if(! entry.hadRecentInput) { cls += entry.value;console.log('Current CLS value:', cls, entry);
}
}
}).observe({type: 'layout-shift'.buffered: true});
Copy the code
How can CLS be improved
First, the most common factors that affect CLS scores are:
- A picture of an unspecified size
- Unspecified size ads, embedded elements, iframe
- Dynamically inserting content
- Custom fonts (raise FOIT/FOUT)
- The action of waiting for a network response before updating the DOM
Therefore, the improvement methods include:
- Set the size of the image from the start, or leave plenty of space. This ensures that the browser allocates the correct amount of space in the document when loading the image. You can also use
unsize -media
Feature policies enforce this behavior in browsers that support feature policies. - Do not insert content above existing content unless in response to user interaction. This ensures that any typographical shifts can be expected.
- Use transform animation properties in preference to animation properties that trigger layout changes. Transitions are animated to provide context and continuity from state to state.
- Load web fonts as early as possible to avoid FOIT and FOUT
- Work with UI colleagues to avoid layout offsets in interactions
Note: Most of this article has been translated from the article web.dev/ CLS /
The resources
- web.dev/cls/
- zhuanlan.zhihu.com/p/207163394
- Web. Dev/optimize – cl…
- Developers.google.com/publisher-t…
The last
- Welcome to add my wechat (Winty230), pull you into the technology group, long-term exchange learning…
- Welcome to pay attention to “front-end Q”, seriously learn front-end, do a professional technical people…