CSS font-family
Property
The font-family
property in CSS specifies the typeface used for text. It allows you to define primary and fallback fonts to ensure consistent typography across different devices and browsers.
1. Syntax
- Primary Font: The first font choice.
- Fallback Font: Alternative fonts in case the primary font is unavailable.
- Generic Family: A broad font category (e.g.,
serif
,sans-serif
,monospace
).
2. Font Categories (Generic Families)
Generic Family | Description |
---|---|
serif | Fonts with decorative strokes (e.g., Times New Roman). |
sans-serif | Clean, modern fonts without strokes (e.g., Arial). |
monospace | Fixed-width fonts where each character takes up the same space (e.g., Courier). |
cursive | Script-like, flowing fonts (e.g., Brush Script). |
fantasy | Decorative or creative fonts (e.g., Papyrus). |
3. Example Usage
A. Specifying Multiple Fonts
✅ Uses Arial first. If unavailable, it falls back to Helvetica, then to any sans-serif
font.
B. Using a Custom Web Font (Google Fonts)
✅ Loads the Roboto font from Google Fonts.
C. Using System Fonts
✅ Uses system default fonts for better performance.
4. Best Practices
✔ Always include fallback fonts to prevent layout issues.
✔ Use quotation marks around font names with spaces (e.g., "Times New Roman"
).
✔ For web fonts, use @import
or the <link>
tag in HTML.
5. Browser Support
✅ Fully supported in all modern browsers.