How to Import Fonts in CSS: Simple Guide with Examples
To import a font in CSS, use the
@import rule with a URL or the @font-face rule to define a custom font. The @font-face method lets you specify font files directly for better control and browser support.Syntax
The two main ways to import fonts in CSS are:
- @import: Loads a font stylesheet from a URL.
- @font-face: Defines a custom font by linking font files directly.
@import is simple but less flexible. @font-face gives full control over font files and formats.
css
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap'); @font-face { font-family: 'MyFont'; src: url('myfont.woff2') format('woff2'), url('myfont.woff') format('woff'); font-weight: normal; font-style: normal; }
Example
This example shows how to import the Google font 'Roboto' using @import and how to use a custom font with @font-face. The page text uses these fonts.
css
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap'); @font-face { font-family: 'CustomFont'; src: url('https://example.com/fonts/customfont.woff2') format('woff2'); font-weight: normal; font-style: normal; } body { font-family: 'Roboto', sans-serif; margin: 1rem; } h1 { font-family: 'CustomFont', serif; color: #2a2a2a; }
Output
The page displays a heading in the 'CustomFont' font and the body text in the 'Roboto' font loaded from Google Fonts.
Common Pitfalls
Common mistakes when importing fonts in CSS include:
- Using
@importinside CSS files after other rules, which can cause the import to be ignored. - Not providing multiple font formats for better browser support.
- Forgetting to specify
font-familywhen using@font-face. - Using incorrect URLs or missing font files.
Always place @import at the very top of your CSS file and check font URLs carefully.
css
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap'); /* Correct: at top */ /* Wrong: @import after other rules - ignored by browsers */ body { color: black; } @import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
Quick Reference
| Method | Usage | Best For |
|---|---|---|
| @import | Import font stylesheet URL | Quick Google Fonts import |
| @font-face | Define font with font files | Custom fonts with control |
| font-family | Apply imported font to elements | Styling text with fonts |
Key Takeaways
Use @import at the very top of your CSS file to load fonts from URLs.
Use @font-face to define custom fonts by linking font files directly.
Always specify font-family to apply the imported fonts to your text.
Provide multiple font formats in @font-face for better browser support.
Check URLs and file paths carefully to avoid broken fonts.