Chapter 4: Working with Text and Fonts
Setting Font Properties
You can use CSS to control font family, size, weight, and style. Here are some examples of commonly used properties for styling fonts.
/* Setting Font Family */
body {
font-family: Arial, sans-serif;
}
/* Setting Font Size */
h1 {
font-size: 2.5rem;
}
p {
font-size: 1rem;
}
/* Font Weight */
h1 {
font-weight: bold;
}
p.light-text {
font-weight: 300;
}
/* Font Style */
p.italic-text {
font-style: italic;
}
Text Color and Alignment
Using CSS, you can set text color and control text alignment to suit your design. These properties help you adjust how text is displayed on your webpage.
/* Text Color */
h1 {
color: #333;
}
p {
color: #555;
}
/* Text Alignment */
h1 {
text-align: center;
}
p {
text-align: justify;
}
Spacing with Line Height and Letter Spacing
Line height and letter spacing are useful for adjusting the readability of text by controlling the space between lines and letters.
/* Line Height */
p {
line-height: 1.6;
}
/* Letter Spacing */
h1 {
letter-spacing: 2px;
}
p {
letter-spacing: 0.5px;
}
Example: Styling Text for a Webpage
Let’s apply what we’ve learned to style the text on a simple webpage, adjusting font properties, colors, alignment, and spacing.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Styled Text Page</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Welcome to My Styled Page</h1>
</header>
<section>
<p class="light-text">This is a sample paragraph styled with custom font size, color, and spacing.</p>
<p class="italic-text">Adding variety to text styles can improve readability and visual interest.</p>
</section>
</body>
</html>
Experimenting with Text and Font Styling
Now that you know how to style text with CSS, try experimenting with different font families, sizes, colors, and alignments. These properties can dramatically change the look and feel of your webpage, so don’t be afraid to try new styles and see what works best for your design.