The font-family Property
The CSS font-family property is the most essential tool for controlling the typeface of your text. It specifies a priority list of font names for the browser to use when rendering text on your webpage.
Defining a Font Stack
The browser can only display a font if it is installed on the user's computer or if you provide it (we'll cover that in a later lesson). Because you can't guarantee a user has a specific font, you must define a font stack.
A font stack is an ordered list of font families separated by commas. The browser checks the list from left to right, using the first font it finds on the user's system.
The Syntax
selector {
font-family: "Font Name 1", "Font Name 2", generic-family;
}
"Font Name 1": The primary, desired font (e.g.,"Helvetica Neue")."Font Name 2": The fallback font (e.g.,"Arial").generic-family: The required final fallback (e.g.,sans-serif).
Quotation Marks
- Use quotation marks (
""or'') around font names that contain spaces (e.g.,"Times New Roman"). - Font names that are single words (e.g.,
Arial,Verdana) do not strictly need quotes, but using them is harmless.
Understanding Generic Font Families
The generic font family is the last and most critical part of your font stack. It's a required safety net that tells the browser what kind of font to pick if none of the specific named fonts are found.
There are five basic generic families:
| Generic Family | Description | Characteristics | Common Examples |
|---|---|---|---|
serif | Fonts with small decorative strokes (serifs) at the end of letter stems. | Formal, traditional, high readability for long text. | Times New Roman, Georgia |
sans-serif | Fonts without serifs (clean lines). | Modern, clean, highly readable on screens. | Arial, Verdana, Helvetica |
monospace | All characters have the same width. | Technical, used for code blocks and data tables. | Courier New, Consolas |
cursive | Fonts that mimic handwriting or script. | Informal, decorative, low readability. | Comic Sans MS, Brush Script MT |
fantasy | Highly decorative or stylized fonts. | Novelty display only, not for body text. | Impact, Papyrus |
Your font stack must end with a generic font family. This ensures that the user's text will always display using a legible default font, preventing a visual disaster if all your custom fonts fail.
Example Font Stacks
/* Ideal for body text (clean and modern) */
body {
font-family: "Helvetica Neue", Arial, sans-serif;
}
/* Ideal for headings (strong and decorative) */
h1 {
font-family: "Georgia", "Times New Roman", serif;
}
/* Ideal for code blocks and data displays */
code {
font-family: "Consolas", "Courier New", monospace;
}
Interactive font-family Demo
Use the live editor to test different font stacks. See how the browser applies the first font from the list that is available on your computer, falling back to sans-serif if the others are missing.