Using @font-face for Custom Fonts
- CSS Basics
- Selectors & Specificity
- Box Model & Units
- Typography & Text Styling
- Colors & Color Spaces
- Positioning & Stacking Context
- Flexbox
- Grid
- Grid Advanced
- Responsive Design
- Container Queries
- Pseudo-classes & Pseudo-elements
- Modern Selectors
- CSS Custom Properties
- CSS Functions
- Transitions & Animations
- Transforms
- Forms & Input Styling
- CSS Architecture & Methodologies
- Accessibility in CSS
- Performance & Optimization
- View Transitions & Modern APIs
- Cascade Layers & Scope
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.