CSS Web Fonts

Load and optimize custom fonts for consistent branding.

Web fonts allow a website to use fonts that may not be installed on the visitor's device. The browser downloads the required font files when the webpage loads.

Web fonts help you:

  • Create a consistent design across devices
  • Match fonts with your brand
  • Use more font styles than standard system fonts
  • Improve the visual appearance of headings and buttons

Using an Online Font Service

Online font services provide ready-to-use font files and CSS. You normally add a <link> element inside the HTML <head>:

HTML
<link rel="preconnect" href="https://fonts.example.com">
<link rel="stylesheet" href="https://fonts.example.com/css?family=Roboto">

You can then use the font in CSS:

CSS
body {
  font-family: "Roboto", Arial, sans-serif;
}

If Roboto cannot load, the browser tries Arial and then the default sans-serif font.

Using the @font-face Rule

The @font-face rule lets you load a font file from your own website.

CSS
@font-face {
  font-family: "MyWebFont";
  src: url("fonts/my-web-font.woff2") format("woff2");
  font-weight: 400;
  font-style: normal;
}

You can now apply it like any other font:

CSS
h1 {
  font-family: "MyWebFont", sans-serif;
}

The main properties are:

  • font-family – gives the font a name for use in CSS
  • src – provides the location and format of the font file
  • font-weight – identifies its thickness
  • font-style – identifies whether it is normal or italic

Loading Different Font Weights

Each font weight may require a separate file:

CSS
@font-face {
  font-family: "MyWebFont";
  src: url("fonts/regular.woff2") format("woff2");
  font-weight: 400;
}

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

The browser selects the correct file automatically:

CSS
p {
  font-weight: 400;
}

strong {
  font-weight: 700;
}

Font Formats

Common web-font formats include:

  • WOFF2 – modern, compressed, and widely supported
  • WOFF – useful as a fallback for older browsers
  • TTF – supported but often larger
  • OTF – supports advanced typography features

For most modern websites, WOFF2 is the preferred format because its smaller file size can improve loading speed.

Controlling Font Loading

The font-display property controls how text appears while the font downloads:

CSS
@font-face {
  font-family: "MyWebFont";
  src: url("fonts/my-web-font.woff2") format("woff2");
  font-display: swap;
}

With swap, the browser displays a fallback font first and replaces it when the web font is ready. This prevents invisible text during loading.