How to Use Custom Fonts in CSS: Simple Guide
Use the
@font-face rule in CSS to load a custom font by specifying its name and source file. Then apply it using the font-family property on any element to display text with that font.Syntax
The @font-face rule lets you define a custom font by giving it a name and linking to the font file. Then you use font-family to apply that font to elements.
@font-face: declares the custom font.font-family: names the font to use in styles.src: URL to the font file (usually .woff, .woff2, or .ttf).
css
@font-face {
font-family: 'MyCustomFont';
src: url('mycustomfont.woff2') format('woff2');
}
body {
font-family: 'MyCustomFont', sans-serif;
}Example
This example shows how to load a custom font called 'OpenSans' from a local file and apply it to the whole page's text.
css
@font-face {
font-family: 'OpenSans';
src: url('OpenSans-Regular.woff2') format('woff2');
font-weight: normal;
font-style: normal;
}
body {
font-family: 'OpenSans', Arial, sans-serif;
font-size: 1.2rem;
color: #333;
margin: 2rem;
}Output
The page text appears in the OpenSans font if the font file loads correctly, otherwise it falls back to Arial or sans-serif.
Common Pitfalls
Common mistakes include:
- Wrong file path in
srccausing the font not to load. - Not providing font formats for browser support.
- Forgetting to use quotes around font-family names with spaces.
- Not adding fallback fonts in
font-familyfor safety.
Always check the font file is accessible and use multiple formats if possible.
css
@font-face {
font-family: MyFont; /* Missing quotes for multi-word names */
src: url('fonts/myfont.ttf');
}
/* Correct way: */
@font-face {
font-family: 'My Font';
src: url('fonts/myfont.woff2') format('woff2'),
url('fonts/myfont.ttf') format('truetype');
}
body {
font-family: 'My Font', sans-serif;
}Quick Reference
| Property | Description | Example |
|---|---|---|
| @font-face | Defines a custom font | @font-face { font-family: 'MyFont'; src: url('myfont.woff2') format('woff2'); } |
| font-family | Applies the font to elements | body { font-family: 'MyFont', sans-serif; } |
| src | URL and format of font file | src: url('font.woff2') format('woff2'); |
| font-weight | Weight of the font (normal, bold) | font-weight: normal; |
| font-style | Style of the font (normal, italic) | font-style: italic; |
Key Takeaways
Use @font-face to load custom fonts by specifying font-family and src.
Always include fallback fonts in font-family for better reliability.
Check font file paths and formats to avoid loading errors.
Quote font-family names if they contain spaces.
Provide multiple font formats for wider browser support.