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:
1️⃣ Font Family
The font-family property defines which typeface your text uses.
Syntax:
selector {
font-family: font1, font2, fallback-font;
}
serif, sans-serif, monospace, cursive, fantasyExample:
p {
font-family: Arial, sans-serif;
}
Explanation:
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/heightExample:
h1 {
font-size: 36px;
}
p {
font-size: 1.2em;
}
1em = the size of the parent element1.2em = 20% bigger than parent3️⃣ 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;
}
<!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>