Choosing the right font can make or break the visual appeal and readability of a website. Whether you’re aiming for elegance, boldness, or clarity, fonts help express the tone of your content. In CSS, you can change the font of any HTML element using the font-family
property.
In this blog, you’ll learn what the font-family
property does, how to use it effectively, and best practices for defining font stacks.
๐ฏ The CSS Property: font-family
The font-family
property in CSS is used to specify the typeface (font) of an HTML element.
โ Basic Syntax:
selector {
font-family: "Font Name", fallback-font, generic-family;
}
selector
: The element to which the style applies (e.g.,p
,h1
,.title
)"Font Name"
: The preferred fontfallback-font
: Optional secondary fontsgeneric-family
: A generic fallback likeserif
,sans-serif
, ormonospace
๐งพ Example:
HTML:
<p class="custom-text">This text uses a custom font.</p>
CSS:
.custom-text {
font-family: "Georgia", "Times New Roman", serif;
}
In this example:
- The browser first tries Georgia.
- If unavailable, it tries Times New Roman.
- If both fail, it defaults to a generic serif font.
๐ Using Web Fonts (e.g., Google Fonts)
To use a custom web font like Roboto, you can import it from Google Fonts:
Step 1: Add the font link in <head>
:
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
Step 2: Apply it with CSS:
body {
font-family: 'Roboto', sans-serif;
}
๐ก Common Generic Font 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 | Each letter takes equal space (e.g., Courier) |
cursive | Script-style fonts |
fantasy | Decorative or playful fonts |
๐ง Tips for Using font-family
- Always specify fallback fonts to ensure consistent appearance across devices.
- Use quotation marks if the font name has spaces (e.g.,
"Open Sans"
). - Pair fonts with care โ balance readability and aesthetics.
๐งพ Complete Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Font Example</title>
<link href="https://fonts.googleapis.com/css2?family=Open+Sans&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Open Sans', Arial, sans-serif;
}
</style>
</head>
<body>
<p>This text is styled with the 'Open Sans' font.</p>
</body>
</html>
๐ Conclusion
The CSS property used to change the font of an element is:
font-family
It allows you to specify both custom fonts and fallback options, giving you complete control over your websiteโs typography.