Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 139 ยท Text and Fonts

Web Fonts

Load your own typefaces with @font-face, serve WOFF2, control loading with font-display, use variable fonts, and keep web fonts fast by self-hosting them.

In Fonts you picked from typefaces that are already installed on the reader's device. That is fast and reliable, but it limits your choice. Web fonts let you ship your own font files with your site, so every visitor sees the same typeface, whether it is a brand font, a distinctive headline face or a font that covers a particular script.

That freedom has a cost: font files must be downloaded before text can render in them. In this lesson you will learn how to declare a font with @font-face, which file format to use, how font-display decides what readers see while fonts load, how variable fonts replace a whole family of files, and how to keep everything fast.

Declaring a font with @font-face

@font-face is an at-rule that teaches the browser about a font: what to call it and where to find its file. It does not apply the font to anything; you still use font-family for that.

CSS
@font-face {
  font-family: "Harbor Sans";             /* the name you will use */
  src: url("/fonts/harbor-sans.woff2") format("woff2");
  font-weight: 400;
  font-style: normal;
  font-display: swap;
}

body {
  font-family: "Harbor Sans", system-ui, sans-serif;
}

The key descriptors are:

  • font-family โ€“ any name you like. It only has to match what you use later.
  • src โ€“ one or more sources, tried in order. url() points to a file; local() names a font that may already be installed on the device.
  • font-weight and font-style โ€“ which weight and style this file provides.
  • font-display โ€“ what to show while the file loads (more on this below).

The browser downloads a font file lazily: only when some text on the page actually needs it. Declaring ten @font-face rules costs nothing until you use them.

One family, several files

A traditional (static) font comes as one file per weight and style. You describe each file with its own @font-face rule, all sharing the same family name:

CSS
@font-face {
  font-family: "Harbor Sans";
  src: url("/fonts/harbor-sans-regular.woff2") format("woff2");
  font-weight: 400;
  font-style: normal;
}
@font-face {
  font-family: "Harbor Sans";
  src: url("/fonts/harbor-sans-bold.woff2") format("woff2");
  font-weight: 700;
  font-style: normal;
}
@font-face {
  font-family: "Harbor Sans";
  src: url("/fonts/harbor-sans-italic.woff2") format("woff2");
  font-weight: 400;
  font-style: italic;
}

Now font-weight: bold and <em> pick the right file automatically. A common mistake is naming them "Harbor Sans Bold" and "Harbor Sans Italic": then <strong> text gets a synthetic bold of the regular file instead of the real bold design.

You can see this mechanism in action with local(), which maps your own family name to fonts already on the device. The demo below builds a family called "Reading" out of installed serif fonts. (Which ones you get depends on your system.)

@font-face with local()

Why the demos don't download fonts. The editor's preview runs in a locked-down sandbox, and you should never hotlink font files from other people's servers in any case. Real projects host their own .woff2 files, as described at the end of this lesson. The read-only examples show the exact syntax you would use.

File formats: just use WOFF2

Over the years fonts have been shipped as TTF, OTF, EOT, SVG and WOFF. Today you need one format: WOFF2. It is a compressed wrapper around a normal font, supported by every current browser, and usually 30% or more smaller than the older WOFF.

The format("woff2") hint lets a browser skip sources it can't use without downloading them. Old snippets with five src entries and EOT hacks for Internet Explorer can be deleted.

If you have a .ttf or .otf file from a type foundry, convert it to WOFF2 with a font tool, and check that the font's license allows web use. Many commercial fonts require a separate web license.

font-display: what happens while fonts load

Between "the page needs this font" and "the file has arrived", the browser has to decide what to show. font-display controls that decision, using two periods:

  • A block period, when text is drawn invisibly while the browser waits.
  • A swap period, when text is shown in a fallback font and swapped once the web font arrives.
Value Block period Swap period Good for
auto Browser's choice (often about 3s) Long Rarely what you want
block About 3s Infinite Icon fonts, where a fallback would show nonsense
swap Almost none Infinite Headings and brand text that must use the font
fallback Very short (~100ms) About 3s Body text: swap if fast, otherwise keep the fallback
optional Very short (~100ms) None Body text where speed beats exact appearance

With swap, readers see text immediately in a fallback font, then a "flash" as it changes. With optional, a slow connection simply never switches, but the font is cached for the next page. Invisible text (block) is the worst experience for readers on slow networks, so avoid it for content.

You can watch the font loading process from JavaScript through document.fonts. Even in the sandbox, it reports the local() font you declared:

Inspecting fonts from JavaScript

A status of loaded means the browser found one of the local fonts; error means none of them exist on your device, and the generic monospace fallback is in use.

Reducing layout shift

When the web font replaces the fallback, the text often changes width, and paragraphs reflow. Two tools reduce that jump:

  1. Pick a fallback that looks similar. A narrow web font should fall back to a narrow system font.
  2. Adjust the fallback's metrics with override descriptors in a second @font-face that wraps a local font:
CSS
@font-face {
  font-family: "Harbor Sans Fallback";
  src: local("Arial");
  size-adjust: 104%;        /* scale glyphs to match the web font's width */
  ascent-override: 92%;     /* match the line box height */
  descent-override: 24%;
  line-gap-override: 0%;
}

body {
  font-family: "Harbor Sans", "Harbor Sans Fallback", sans-serif;
}

The percentages come from comparing the two fonts' metrics; several free tools calculate them for you. When they are right, the swap is almost invisible.

Variable fonts

A variable font packs a whole range of designs into one file. Instead of separate regular, semibold and bold files, it has a weight axis that can produce any value in between. Many variable fonts also have axes for width, slant or optical size.

CSS
@font-face {
  font-family: "Harbor Sans";
  src: url("/fonts/harbor-sans-var.woff2") format("woff2");
  font-weight: 100 900;      /* a range, not a single value */
  font-style: normal;
  font-display: swap;
}

h1   { font-weight: 780; }   /* any number in the range works */
.ui  { font-weight: 450; }

Standard axes map to normal properties: weight to font-weight, width to font-stretch, slant to font-style: oblique <angle>, and optical size to font-optical-sizing. For custom axes, use font-variation-settings with the axis tag, for example font-variation-settings: "GRAD" 50;. Prefer the regular properties whenever one exists, because font-variation-settings overrides them all at once.

Many operating systems now ship variable system fonts, so you can often try the weight axis without loading anything. Drag the slider:

Any weight you like

If your system font is variable, the weight changes smoothly at every step. If it is a static font, it jumps between the few weights that exist. That difference is exactly what a variable font buys you.

Keeping web fonts fast

Web fonts are often among the largest render-critical files on a page. These habits keep them in check:

  • Self-host your fonts. Serve the .woff2 files from your own domain. You avoid an extra connection to a third-party server, you control caching, and you don't send visitors' IP addresses to someone else. Many font services let you download the files for exactly this purpose.
  • Load fewer files. Every weight and style is another download. Two or three files (or one variable font) is a sensible budget.
  • Subset. If you only need Latin characters, a subset file can be a fraction of the full size. unicode-range tells the browser which characters a file covers, so it only downloads the subsets the page actually uses:
CSS
@font-face {
  font-family: "Harbor Sans";
  src: url("/fonts/harbor-sans-latin.woff2") format("woff2");
  unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+2013-2014, U+20AC;
}
  • Preload the one font that matters most, usually the body text font, so the browser starts fetching it before it parses the CSS. The crossorigin attribute is required for fonts, even on your own domain:
HTML
<link rel="preload" href="/fonts/harbor-sans-var.woff2" as="font" type="font/woff2" crossorigin>
  • Cache for a long time. Font files rarely change. Give them versioned file names and a long Cache-Control lifetime.
  • Consider not using one. A good system font stack has zero download cost. For body text in particular, it is often the right answer.

Resource Loading covers preloading and other hints in more detail.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does an @font-face rule do by itself?

    @font-face only declares the font. The browser downloads the file lazily, once some text actually uses that family.
  2. 2. You have separate regular and bold files. How should you declare them?

    Sharing one family name lets the browser pick the right file for each weight. Different names force you to switch families manually and cause synthetic bold.
  3. 3. Which font format should a modern site serve?

    WOFF2 is compressed, supported by every current browser, and the only format you need today.
  4. 4. Which font-display value never swaps to the web font if it doesn't arrive almost immediately?

    optional has a tiny block period and no swap period. If the font is late, the page keeps the fallback, and the cached font is used on later pages.
  5. 5. Which is NOT a good way to make web fonts load faster?

    Every extra file is another download. Load only the weights you use, or one variable font that covers the range.

Summary

  • @font-face declares a font's name, source files, weight and style; font-family applies it.
  • Give all files of one family the same name and describe each with font-weight and font-style.
  • Serve WOFF2 only, and check the font's license allows web use.
  • font-display controls what readers see while a font loads; swap, fallback and optional avoid invisible text.
  • Metric overrides such as size-adjust make the swap from fallback to web font less jumpy.
  • Variable fonts provide whole ranges of weights (and other axes) in one file.
  • Self-host, subset, preload the critical font, cache long, and remember that a system font stack costs nothing.

Next: Line Height and Vertical Rhythm, where you give your text room to breathe.