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 fontascent-override
defines the height above the baseline of a fontdescent-override
defines the height below the baseline of the font
In NextJs 13 the font library uses this in order to avoid the layout shift.
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.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.
📖 50 Javascript, React and NextJs Projects
Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.