Load a web font properly

Declare a web font and use it only for headings.

What to build

An @font-face rule and a rule that uses it.

Requirements

  • An @font-face rule, naming the family Brand.
  • Its src is url("brand.woff2") with format("woff2").
  • It uses font-display: swap.
  • h1 uses Brand, falling back to Arial and then sans-serif.
  • p does not use Brand.

Constraints

Declare the @font-face rule before the rule that uses it.

Example

See the second code block in the lesson. The file does not exist here, so the fallback is what you will see, and that is the fallback working as designed.

Why it works

The browser only downloads the font if something on the page uses it, and swap means nobody waits for it to read the headline.

Hints

Hint 1

@font-face names the font and says where the file is.

Hint 2

The name you invent is the name you use in font-family.

Hint 3

A fallback belongs after your custom font.

Solution

Show one correct solution (try it yourself first)
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Web font</title>
  <style>
    @font-face {
      font-family: "Brand";
      src: url("brand.woff2") format("woff2");
      font-display: swap;
    }
    h1 { font-family: "Brand", Arial, sans-serif; }
  </style>
</head>
<body>
  <h1>Headline</h1>
  <p>Body text.</p>
</body>
</html>

Lesson: Text and fonts →