Fonts in CSS control how text appears on a webpage. Understanding fonts is essential because text is a major part of any website.
There are three main things to control:
- Font family → Which typeface to use
- Font size → How big the text is
- Font style → Normal, italic, or oblique
1️⃣ Font Family
The font-family property defines which typeface your text uses.
Syntax:
selector {
font-family: font1, font2, fallback-font;
}
- Always include a fallback font in case the first one isn’t available.
- Generic families:
serif,sans-serif,monospace,cursive,fantasy
Example:
p {
font-family: Arial, sans-serif;
}
Explanation:
- Try Arial first
- If not available, use any sans-serif font
Popular Font Families:
TypeExamplesSerifTimes New Roman, GeorgiaSans-SerifArial, HelveticaMonospaceCourier New, ConsolasCursivePacifico, Comic SansFantasyImpact, Jokerman
2️⃣ Font Size
The font-size property defines how big the text appears.
Common Units:
px→ Pixels (fixed size)em→ Relative to parent font sizerem→ Relative to root font size%→ Relative to parent elementvw/vh→ Relative to viewport width/height
Example:
h1 {
font-size: 36px;
}
p {
font-size: 1.2em;
}
1em= the size of the parent element1.2em= 20% bigger than parent
3️⃣ Font Style
The font-style property defines slant of text.
Values:
normal→ Defaultitalic→ Italicoblique→ Slight slant (less supported)
Example:
p {
font-style: italic;
}
4️⃣ Font Weight
Although not requested, it’s often used with fonts.
p {
font-weight: normal; /* 400 */
font-weight: bold; /* 700 */
}
Numeric values range from 100 to 900 (thin to extra-bold).
5️⃣ Combining Font Properties
You can use multiple font properties together:
h1 {
font-family: 'Georgia', serif;
font-size: 36px;
font-style: italic;
font-weight: bold;
}
6️⃣ Using Google Fonts
Example: Adding Roboto font from Google Fonts
HTML:
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
CSS:
body {
font-family: 'Roboto', sans-serif;
}
Compilation of Entire Code
<!DOCTYPE html>
<html>
<head>
<title>CSS Fonts Example</title>
<style>
body {
font-family: Arial, sans-serif;
font-size: 16px;
line-height: 1.5;
margin: 20px;
}
h1 {
font-family: 'Georgia', serif;
font-size: 36px;
font-style: italic;
font-weight: bold;
color: darkblue;
}
h2 {
font-family: 'Verdana', sans-serif;
font-size: 28px;
font-style: normal;
font-weight: 600;
color: darkgreen;
}
p {
font-family: 'Courier New', monospace;
font-size: 18px;
font-style: normal;
font-weight: normal;
color: #333333;
}
</style>
</head>
<body>
<h1>Main Heading</h1>
<h2>Subheading</h2>
<p>This paragraph uses a monospace font. You can control its size, style, and family.</p>
</body>
</html>