SEO - How to avoid layout shift when using fonts

When using the Google web fonts you can take several steps to ensure that your page's layout remains stable as the font loads.

avatar
Oscar Quinteros
SHARE:
Thinking...
Thinking...

1. Use font-display: swap

   - This CSS property ensures that a fallback font is used immediately, and once "Inter" is fully loaded, it will replace the fallback. This prevents layout shifts caused by a delay in loading the font.

@font-face {
    font-family: 'Inter';
    font-style: normal;
    font-weight: 400;
    font-display: swap;
    src: url('https://fonts.gstatic.com/s/inter/v12/UcCo3Fwrn7lO6a1l7L1YIg.woff2') format('woff2');
}   

2. Preload the Font

   - Preloading the font ensures that it's loaded as soon as possible, reducing the time the browser uses a fallback font, which can cause layout shifts.

<link rel="preload" ref="https://fonts.gstatic.com/s/inter/v12/UcCo3Fwrn7lO6a1l7L1YIg.woff2" as="font" type="font/woff2" crossorigin="anonymous">

3. Use Fallback Fonts Carefully

   - Choose a fallback font that closely matches the metrics (size, weight, line height) of "Inter." This reduces the visual difference between the fallback and the final font, minimizing layout shifts.

body {
 font-family: 'Inter', Arial, sans-serif;
}   

4. Font Loading Strategy

   - Font Face Observer: Use a JavaScript library like Font Face Observer to control when the font is applied after it has loaded, ensuring layout stability.

   const font = new FontFaceObserver('Inter');
  
    font.load().then(() => {
        document.documentElement.classList.add('font-loaded');
    });
  
    /* In your CSS /  
    body {
        font-family: Arial, sans-serif; /
Fallback font */
    }
    .font-loaded body {
        font-family: 'Inter', Arial, sans-serif;
    }

5. CSS Containment

   - Use CSS containment (contain: layout;) to isolate parts of your layout where font shifts might occur, reducing the impact on the overall layout.

    .text-container {
        contain: layout;
    }   

6. Use font-size-adjust (if applicable)

   - If the fallback font's x-height differs significantly from "Inter," you can use the font-size-adjust property to maintain a consistent visual size.

body {      font-family: 'Inter', Arial, sans-serif;      font-size-adjust: 0.5; /* Adjust this value based on your needs */    }    

By implementing these strategies, you can minimize or eliminate layout shifts caused by the loading of the Inter font.

Visited 41 times
0 0

Comments

Please register to comment. Thanks!

More From Author

Related Articles