CSS @font-face Tutorial
The @font-face rule lets you specify custom fonts for your website. Here's how to use it effectively:
Basic Syntax
@font-face {
font-family: 'MyCustomFont';
src: url('fonts/mycustomfont.woff2') format('woff2'),
url('fonts/mycustomfont.woff') format('woff');
font-weight: normal;
font-style: normal;
font-display: swap;
}
Using the Font
body {
font-family: 'MyCustomFont', Arial, sans-serif;
}
h1 {
font-family: 'MyCustomFont', Georgia, serif;
}
Multiple Weights
/* Regular */
@font-face {
font-family: 'MyFont';
src: url('myfont-regular.woff2') format('woff2');
font-weight: 400;
font-style: normal;
}
/* Bold */
@font-face {
font-family: 'MyFont';
src: url('myfont-bold.woff2') format('woff2');
font-weight: 700;
font-style: normal;
}
/* Italic */
@font-face {
font-family: 'MyFont';
src: url('myfont-italic.woff2') format('woff2');
font-weight: 400;
font-style: italic;
}
Tip: Use the CSS @font-face Generator to automatically generate this code for your fonts.
Font Display Strategies
The font-display property controls how fonts are displayed while loading:
font-display: swap
Shows fallback immediately, swaps to custom font when ready. Best for body text.
font-display: block
Brief invisible text period, then custom font. Use for icon fonts.
font-display: fallback
Very short block period, then fallback. May not swap if font loads slowly.
font-display: optional
Uses font only if already cached. Best for non-essential decorative fonts.