How to Use @font-face in CSS: Simple Guide with Examples
Use the
@font-face rule in CSS to load custom fonts by specifying a font name and the font file URL. Then apply the font using the font-family property in your styles.Syntax
The @font-face rule lets you define a custom font by giving it a name and linking to the font file. You then use that name in your CSS styles.
- font-family: The name you choose for the font.
- src: The URL to the font file (usually .woff, .woff2, .ttf).
- font-weight and font-style: Optional properties to specify font variations.
css
@font-face {
font-family: 'MyCustomFont';
src: url('mycustomfont.woff2') format('woff2');
font-weight: normal;
font-style: normal;
}Example
This example shows how to load a custom font named 'OpenSans' from a URL and apply it to the whole page.
css
@font-face {
font-family: 'OpenSans';
src: url('https://fonts.gstatic.com/s/opensans/v29/mem8YaGs126MiZpBA-UFVZ0e.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}
body {
font-family: 'OpenSans', sans-serif;
font-size: 1.2rem;
color: #333;
margin: 2rem;
}Output
The page text appears in the OpenSans font, a clean and readable sans-serif style.
Common Pitfalls
Common mistakes when using @font-face include:
- Not providing the correct path or URL to the font file, causing it not to load.
- Forgetting to specify the font format, which helps browsers understand the file type.
- Not including fallback fonts in
font-family, which can cause poor display if the custom font fails. - Using font files that are too large, slowing down page load.
Always test your font loading on different browsers and devices.
css
@font-face {
font-family: 'BadFont';
src: url('wrongpath/font.woff'); /* Wrong path, font won't load */
}
/* Correct way */
@font-face {
font-family: 'GoodFont';
src: url('fonts/goodfont.woff2') format('woff2');
}Quick Reference
| Property | Description |
|---|---|
| font-family | Name you assign to the custom font |
| src | URL and format of the font file |
| font-weight | Optional: weight like normal, bold, 400, 700 |
| font-style | Optional: style like normal, italic, oblique |
Key Takeaways
Use @font-face to load custom fonts by specifying font-family and src URL.
Always include font format in src for better browser support.
Provide fallback fonts in font-family for safety.
Check font file paths carefully to avoid loading errors.
Keep font files optimized for faster page loading.