How to Use CSS @font-face: A Complete Guide to Custom Web Fonts

The @font-face rule in CSS allows you to use custom fonts on a webpage, ensuring consistent typography across different devices and browsers. This guide covers how to implement, optimize, and best use @font-face for web typography.

1. Defining a Custom Font with @font-face

To load a custom font, define it in your CSS:

css
12345678
@font-face {
  font-family: 'CustomFont';
  src:
    url('fonts/custom-font.woff2') format('woff2'),
    url('fonts/custom-font.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}
  • font-family: Name assigned to the font.
  • src: Specifies font file paths and formats.
  • font-weight & font-style: Define variations (optional).

2. Applying the Font

Once defined, use it in your styles:

css
123
body {
  font-family: 'CustomFont', sans-serif;
}

3. Best Practices for @font-face

a) Use Multiple Font Formats for Compatibility

Older browsers may not support modern formats. Provide fallbacks:

css
1234567
@font-face {
  font-family: 'CustomFont';
  src:
    url('fonts/custom-font.woff2') format('woff2'),
    url('fonts/custom-font.woff') format('woff'),
    url('fonts/custom-font.ttf') format('truetype');
}

b) Load Fonts Efficiently

  • Prefer WOFF2 format for modern browsers (better compression).
  • Use font-display: swap to prevent rendering delays:
    css
    12345
    @font-face {
      font-family: 'CustomFont';
      src: url('fonts/custom-font.woff2') format('woff2');
      font-display: swap;
    }
  • Host Locally: Self-hosting fonts is faster than external CDNs.

4. Using Variable Fonts

Variable fonts allow flexibility in weight and style within a single file:

css
12345
@font-face {
  font-family: 'CustomFont';
  src: url('fonts/custom-font.woff2') format('woff2');
  font-weight: 100 900;
}

This allows dynamic font-weight control:

css
1234
h1 {
  font-family: 'CustomFont', sans-serif;
  font-weight: 700;
}

5. Accessibility & Performance Considerations

  • Limit the Number of Custom Fonts: Too many fonts can slow page load times.
  • Use System Fonts as a Fallback: Provide alternatives in font-family.
  • Optimize Font Loading: Use preload techniques and avoid blocking resources.

Conclusion

Using @font-face, you can create a unique and consistent web typography experience. By optimizing performance, ensuring compatibility, and following best practices, you can enhance readability and design without compromising speed.