Using @font-face for Custom Fonts

Why @font-face Exists

Browsers only render fonts that are either installed on the visitor's device or delivered by the website itself. @font-face lets a stylesheet load a specific font file and give it a name that other rules can reference, so a design is not limited to whatever fonts happen to already be on someone's computer.

Basic Syntax

@font-face {
  font-family: "Inter";
  src: url("/fonts/Inter-Regular.woff2") format("woff2");
  font-weight: 400;
  font-style: normal;
  font-display: swap;
}

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

Loading Multiple Weights

Each weight or style of a font is usually a separate file, so a typeface with regular and bold versions needs two @font-face blocks that share the same font-family name but declare different font-weight values.

@font-face {
  font-family: "Inter";
  src: url("/fonts/Inter-Bold.woff2") format("woff2");
  font-weight: 700;
}

Once both are declared, simply writing font-weight: bold on an element automatically picks the matching bold file.

The font-display Property

font-display: swap tells the browser to show text immediately using a fallback font, then swap in the custom font once it finishes downloading, instead of leaving text invisible while waiting. This avoids a poor experience on slow connections.

A Performance Tip

Custom fonts add extra network requests and can slow down the first paint of a page. Using the modern .woff2 format (smaller than older formats) and only loading the weights actually used in the design keeps this cost under control.

Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Continue reading

All CSS notes →

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.