How to Set Font-Family in CSS: Simple Guide
Use the
font-family property in CSS to specify the font for text. You list fonts by priority, separated by commas, and end with a generic family like serif or sans-serif as a fallback.Syntax
The font-family property sets the font for an element's text. You can list multiple fonts separated by commas. The browser uses the first available font. Always end with a generic family as a fallback.
- font-family: property name
- font names: names of fonts in quotes if they have spaces
- generic family: fallback like
serif,sans-serif, ormonospace
css
selector {
font-family: "Font Name", Arial, sans-serif;
}Example
This example shows how to set a paragraph's font to use "Comic Sans MS" first, then Arial, and finally any cursive font if the others are not available.
css
html {
font-size: 1.2rem;
}
p {
font-family: "Comic Sans MS", Arial, cursive;
color: #333;
}Output
A paragraph with text shown in Comic Sans MS font if available, otherwise Arial, or a cursive font.
Common Pitfalls
Common mistakes include:
- Not using quotes around font names with spaces (e.g.,
"Times New Roman"must be quoted). - Forgetting to add a generic fallback font family.
- Listing fonts in the wrong order, which can cause unexpected fonts to show.
Always check that the fonts you list are installed or available via web fonts.
css
/* Wrong way: missing quotes and no fallback */ p { font-family: "Times New Roman", Arial; } /* Right way: quotes and fallback */ p { font-family: "Times New Roman", Arial, serif; }
Quick Reference
Remember these tips when setting font-family:
- Use quotes for font names with spaces.
- List fonts from most preferred to least.
- Always end with a generic family.
- Test on different devices to ensure fonts appear as expected.
Key Takeaways
Use the font-family property to set text fonts in CSS.
List multiple fonts separated by commas, ending with a generic fallback.
Put quotes around font names that have spaces.
Always include a generic font family like serif or sans-serif as a fallback.
Check font availability to ensure consistent display across devices.