Checkout my CSS Grid By Example and Getting Started With React video courses on Skillshare. Sign up now and get one free month of Skillshare.

How to fix CLS for font swapping with CSS size-adjust

When working with custom fonts we can easily get into CLS (Cumulative Layout Shift) issues. And Google will penalize our SEO score for this.

Let's take an example when the same text is rendered with the default Arial font and also with the custom Lekton Google font.

As you can see in the below image the Arial font will make the text to be taller than the same text rendered with the Lekton Google font.

And this will happen even if we set the font-size property to be the same for both paragraphs:

p {
    font-size: 1rem;
}

In this case, if we use font display swapping for the Google font we will get a layout shift.

In order to fix this we can use a mix of CSS properties like:

  • size-adjust CSS that defines a multiplier for glyph outlines and metrics associated with a font
  • ascent-override defines the height above the baseline of a font
  • descent-override defines the height below the baseline of the font

In our case what we can do is define a new font face:

@font-face {
    font-family: "Lekton-fallback";
    size-adjust: 111.84%;
    ascent-override: 63%;
    src: local("Arial");
}

In order to create a seamless swap we can get the values from this size-adjust calculator by Malte Ubl. Or if you have too much time to spare try to manually adjust the values 🤯.

This Lekton-fallback is a customized version of the basic Arial font that will be used to first render the text until the custom Google font is fully loaded. Given that is customized to have the exact size as the custom Lekton font it will not cause a layout shift when swapped:

You can checkout the full codepen here.

Web.dev has a great article about the CSS size-adjust. Also, keep in mind that you optimize the font loading even more with preconnect or loading just the needed chacaters for writing a specific text.

Home Screencasts Best of Newsletter Search X