How to Better Optimize Cumulative Layout Shift

Publift
November 22, 2021

Have you ever visited a website and were about to click on a hyperlink only for the layout to shift suddenly? If you have, your page experience likely went as follows:

Although you initially meant to fact-check the article on its sources, you’re now whisked away to another, unknown place filled with credit card offers because you clicked on an ad instead.

Unless you clear your cookie cache, you’ll see MasterCard ads until the end of time.

Without that layout shift, this whole problem could have been avoided, and Google agrees.

For Google, user experience (UX) is one of their top priorities, which is why Cumulative Layout Shift (CLS), along with two other Core Web Vitals, rolled out in June 2021.

However, just like several other aspects of user experience, Cumulative Layout Shift isn’t understood by many. It’s why websites are often stuffed with intrusive ads and banners that completely ruin page experience, but the Core Web Vitals are here to change that.

What is Cumulative Layout Shift (CLS)?

Since Google placed a ranking metric onto user experience, publishers are asking themselves, “What is Cumulative Layout Shift?” and “How can I use it to impact my website ranking?”

Cumulative Layout Shift is a Core Web Vital metric that sums all layout shifts on a page, except those not caused by user interaction, with a speed-dependent calculation.

CLS looks at the proportion of the impacted viewport and movement distance.

How Do Layout Shifts Affect User Interaction?

Unexpected layout shifts are not only frustrating, but they significantly impact user interaction.

When elements start shifting around the page, they throw off users and make it difficult for them to maneuver websites. Some websites are so bloated with ads that they may shift your cursor towards the “Add to Cart” or “Purchase” button, which may result in an accidental purchase.

Such experiences are visually jarring and make for a bad first impression. To ensure your users don’t float all over your page content, start tracking your sites' CLS score.

How is CLS Calculated?

The CLS threshold also determines the layout shift score and your ranking factor. Cumulative Layout Shift is a relevant metric for user experience and therefore affects your SEO performance.

Of the six metrics Google's PageSpeed tracks, CLS accounts for 15% of its score, making it the 3rd most crucial speed-based metric.

CLS summarizes all unexpected content shifts that happen on the page. To pass Google's assessment, users need a high CLS grade.

  • Good – below 0.1,
  • Needs Improvement – between 0.1 and 0.25,
  • Poor – above 0.25.

The number value for CLS represents the severity of each movement. When layout shifts occur, Google calculates how far the content within the viewport moved during the page's lifetime.

What is the Ideal Threshold Score?

A good CLS score is anything below 0.1. Although Google recommends keeping your score under 0.1, the ideal threshold score is 0 for fully static pages. It’s easier to earn this score when you have little to no dynamically injected content on your pages.

With code, you can add several ads, banners, and forms onto your page and still avoid large layout shifts.

Whenever an element visible in the viewport changes its start position, the shift is recorded as an unstable element.

Keep in mind that layout shifts are only recorded if a factor causes visible elements to change their positions on the page. If new Document Object Model elements (DOM elements) are added, or existing elements change size, the CLS score is unaffected.

Layout shift scores are determined by two layout shift measurements: impact fraction and distance fraction. You need to calculate the impact region before the impact fraction.

Impact Fraction Calculation

Calculate the impact region, or the space affected by layout shifts, by getting a number value for the impact area. Then, to determine the impact fraction, divide the impact area by the viewport area. The viewport is the section of the page that remains visible without scrolling down.

Impact Fraction = [Area of Impact Region [300 x 400]] / [Area of Viewport [500 x 600]]

Impact fraction only accounts for the movement itself and doesn’t consider how distracting the movement is. Distance fraction along with move distance solves this issue.

Distance Fraction Calculation

Find the move distance first by defining how far the elements moved. Then, divide the max move distance by the viewport’s total height to determine the distance fraction.

Distance Fraction = [Max. Move Distance [100]] / [Height of ViewPort [600]]

Now, use the solutions found in both formulas to complete the layout shift calculation.

Layout Shift Calculation

To determine the layout shift score for one animation, multiply the impact fraction by the distance fraction. However, if you want to calculate the total Cumulative Layout Shift, take all layout shift scores for the total amount of animation frames and add them.

Although adding all these layout shift scores was effective, it didn’t account for Single Page Applications that are long-lived, which made the formula too unfair for certain users.

To account for this, Google began grouping shifts in session windows, which are time frames in the lifecycle of an existing page.

Layout shifts are then summarized within the session window, meaning CLS score is only impacted during the length of the session.

What’s more, the final CLS score accounts for the max score of one session window, so if a user closes the window during a shift, it isn’t accounted for. Anything that shifts within the input exclusion window, which includes the time it takes to load the page, also isn’t counted.

Other Calculations

There are a few other elements considered in CLS, including:

  • Intentional Changes to the Layout: The input exclusion window ignores shifts that occur within half a second from user input.
  • Layout and Animation Shifts: Google ignores CSS transform changes and animations.
  • Generating Layout Shifts: If layout shifts happen when the page is loading, it may negatively affect your CLS score if it happens outside the exclusion window.
  • Above the Fold Layout Shifts: Google only counts changes within the visible viewport.

To accurately track layout shifts and layout changes, use a CLS measuring tool.

Tools for Measuring CLS

CLS score measuring tools can actively help prevent layout shifts. Software tools measure your existing content and use their respective Cumulative Layout Shift metric performance tab to offer businesses a final CLS score that they can improve on.

Most of the following software solutions interpret lab data, but Google’s PageSpeed Insights also measures field data. Search Console offers a bare-bones Core Web Vitals Report.


Lab data involves collecting performance data in a controlled environment, but since it’s based on predefined conditions, most lab data scores don’t reflect real user experience at 100%

On the other hand, field data is based on aggravated data, which is acquired by combining individual-level data. It’s often used to provide statistical analysis of groups of people and to summarize business data. Although field data is more accurate, it isn’t always available.

The terms “real user data” and “field data” are one and the same, but JavaScript API is its own system. If you have some coding experience, you can use JavaScript API to measure CLS by the minute. Initiate the Layout Instability API if you want to check for unexpected layout shifts.

PageSpeed Insights and Search Console can help you with optimizing CLS and avoiding large layout shifts. The PageSpeed Cumulative Layout Shift Test checks for responsive web design provide more details for web developers and assist you with injecting dynamic content.

An ideal PageSpeed score is achieved when all speed metrics average out to 90 or above. If you notice one or more of your metrics is in orange, focus on improving those areas.

  • Good: 90 or above (green)
  • Needs Improvements: 50 to 90 (orange)
  • Poor: below 50 (red).

On the performance tab, users can see precisely how PageSpeed Insights measure visual stability. PageSpeed uses Chrome User Experience Report, their statistical analysis software, to collaborate metrics that are useful for measuring visual stability as it checks for responsive images, image aspect ratio, web font, font display, initial page load, and much more.

All web vitals placed in the summary tab are weighted differently: FID, Speed Index, and Time to Interactive are scored at 10%, CLS at 15%, LCP at 25%, and Total Blocking Time at 30%. Google doesn’t count shifts that are made from user interactions.

Keep in mind that metrics piggyback off of each other. For example, if LCP and Total Blocking Time are slow, then your loading time will likely tug along at a snail's pace.

How to Reduce Cumulative Layout Shift (CLS)?

To improve cumulative layout shift issues, it’s essential to understand what affects CLS in the first place.  Several factors contribute to poor CLS scores, including:

  • Adding videos and images without dimensions
  • Installing ads, iframes, and embeds without dimensions
  • Actions waiting for a page load or network response to update DOM elements (dynamically injected content)
  • Web fonts causing a flash of invisible text (FOIT) or flash of unstyled text (FOUT), slow system fonts, font loading, or a failing font display

CLS plays a significant role on mobile devices. 77% of Americans have a smartphone, and almost 40% of all eCommerce purchases were made using a mobile device. However, tablets and smartphones are the most challenging devices to optimize.

Due to a weaker CPU, complicated network, and smaller viewport, it can be difficult for mobile coders to determine how much space you need on the page to keep all of your elements visible.

You would need to ensure your video and image attributes shrink based on viewport size.

1. Image Width and Height Attributes

If you don’t specify width and height attributes for your site, the browser won’t know how much space is needed to properly allocate elements while the page is loading.

More than likely, the reserved space won’t be enough, and the display will shift in order for it to fit.

Include image dimensions and video elements to create the correct amount of space.

2. FOUT/FOIT Web Font

It can sometimes take more than two rendered frames for custom text to load, resulting in invisible text or the use of a fallback font. If custom text takes longer to appear than the initial page load allowance, it’ll trigger layout shifts and affect your CLS score and the web font itself.

To solve this issue, use a preload font or system font that's embedded directly into your code.

3. Non-Specified Ads, Iframes, and Embeds Dimensions

Another way to avoid large layout shifts is by specifying ads, iframes, and embeds dimensions. A layout shift occurs when the wrong ad aspect ratio is embedded into the website’s code.

While you may need to account for subtle differences in ad/placeholder sizes and form factors when using media queries, you can reserve space to prevent this problem.

4. How Animations and Dynamic Content

Actions that wait for a web server network response before they populate also cause shifts.

If user input caused layout shift regions to grow, then it won’t count against a CLS score, especially if the shift falls into the same aspect ratio used before the layout shift. However, If coded layout shift entries are accounted for, then you need to reserve space for it.

To learn how to solve layout shift problems in WordPress, continue on to the next section.

How to Fix Cumulative Layout Shift Issues in WordPress?

Coders have several methods they can use to fix Cumulative Layout Shift issues in WordPress. If you have competent coding skills and wish to reduce a Cumulative Layout Shift found on your website, this 10 step process will remove WordPress-specific CLS problems.

Step 1: Learn What Elements are Shifting

Tools like Cumulative Layout Shift Debugger and PageSpeed Insights can show you exactly where shifts are occurring. Alternatively, you could use Chrome Dev Tools and Enable the Layout Shift Regions checkbox, where the shifted elements are highlighted in blue.

Step 2: Disable Asynchronous CSS or Use Critical CSS

Most cache plugins have a setting to load CSS asynchronously, but this can cause FOUC and shift your web font. You can disable CSS delivery in your plugin’s settings.

Devs could also only load critical CSS by disabling mod_pagespeed or generating page-specific critical CSS paths.

Step 3: Host Preloaded Local Fonts

Preloaded fonts don’t allow for optimization. More often than not, these web fonts take forever to load and resort to a fallback font before they populate. Always host fonts locally from your website by using tools like Transfonter or OMGF plugin to paste the font URLs directly.

Step 4: Add Font-Display: Swap to Fonts

Specific web fonts may still load slowly depending on their size, but adding font-display:swap to your font’s CSS will ensure your layout doesn’t shift due to FOIT.

To keep an active font display, install String Locator to search for the problematic font, then add &display=swap to your code.

Step 5: Set Global Font to Mulish in Oxygen Builder

If you’re using Oxygen Build, you can solve your CLS issues by opening your stylesheet and adding ‘Mulish’ in the middle of a text's body like so: body { font-family: 'Mulish', Arial; }

Step 6: Specify Image, Video, and Iframe Dimensions

Simply insert width=”000” height=“000” after the image signifier in the code or width=”000” height=“000 ></iframe> after a video or iframe to ensure your media has enough space.

Step 7: Use CSS Transform Property for Animations

Animations can lead to dramatic layout shifts, and accounting for aspect ratios may not solve your issue. Add the CSS transform property transform:translate() instead of using width + height.

Step 8: Leave Space for Advertisements and Serve Them Properly

Reserve space for ads. Otherwise, advertisements will shift other content on the page when they eventually load.

Google advises creators to leave space for the largest size advertisement configured to serve like so: <div class="ad" style="min-width: 000px; min-height: 050px;"></div>

Step 9: Install a Lightweight GDPR Plugin

GDPR Cookie Compliance software is handy for websites that wish to stay CCPA compliant, but they often cause Cumulative Layout Shift issues.

Heavy GDPR plugins may stack elements on top of each other while loading, so use a lightweight GDPR/CCPA to solve this problem.

Step 10: Hard Code Headers and Menus

Your headers and menus may be adding to your website’s layout shift. Hard coding these aspects into CSS will cause fewer issues for web pages. Most page builders will also cause header and menu shifts, but Elementor and Divi add hard-coding elements for users.

Conclusion

Cumulative Layout Shift (CLS) is one of the three Core Web Vitals created by Google to place user experience front and center for website owners. While CLS and other vital metrics may take some getting used to, CLS can improve a website’s performance and overall load time.

With the use of third-party software, like Lighthouse and Google’s own PageSpeed Insights, users can locate where CLS layout shifts occur. At the same time, software can offer users best practices for improving their overall SEO score, which will help them rank higher.

Users can hard code layout shift fixes or use plugins to improve their CLS score. When your dynamic content stays static, you’ll reduce user frustration and increase overall revenue.

Now that your ads are comfortable in their spots, reach out to Publift to find out how you can boost your ad revenue further by optimizing your ad placement and ad partners.

Calculate your potential