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.

Using the font-display CSS property to optimize custom fonts loading

The custom fonts are great! They give us have unlimited typography options, but they also make our pages slower because we need to download them.

They even cause something called FOUT - flash of unstyled text. This means that while the browser downloads the custom font the text can be invisible or rendered with another font. Either way, when the custom font is loaded that text will change its display causing this flash of unstyled text.

There is a less known CSS property that can be quite useful when dealing with custom font displays. It is called font-display and takes one of the following values:

font-display: block | swap | auto | fallback |optional;
  • font display block: this option will hide the text until the font is fully downloaded. This will cause FOUT - flash of unstyled text
  • font display swap: will use the fallback font until the custom font is fully downloaded. This one will also cause FOUT as the text will change its shape once the custom font replaces the fallback one.
  • font display auto: it will let the browser decide what option to use. From what I've read in this article Firefox will hide the text for a max of 3 sec while Edge will use swap. This is the default option.
  • font display fallback: the browser hides the text for about 100ms, and if the font is not ready it will use the fallback text. It will swap to the new font after it is downloaded
  • font display optional: somehow is the same as a fallback just that for this value the custom font may not be used at all. It will use the user’s connection speed as a determining factor if slower connections are less likely to receive the custom font.

In order to specify the fallback we can do something like:

@font-face { 
    font-family: 'MyWebFont'; 
    url('myfont.woff') format('woff'); 
    font-display: fallback;}

.something {
   font-family: MyWebFont, Arial, Helvetica, sans-serif;
/*Arial,  will act as the fallback font*/

For the main text of the body the optional value seems a good bet. Users will get fast content, and if the custom font download will take too long, they won’t get a page re-layout halfway through reading your article.

By the way, there are also many other things we can do to optimize fonts like using preconnect or loading just the needed characters instead of the full font.

Home Screencasts Best of Newsletter Search X