Text and Fonts
CSS gives you amazing control over how text and fonts appear on your website. You can change everything from the font itself to the size, color, and even the spacing between letters. This section will cover the fundamentals to get you started!
What is Text and Font Styling?
Text and font styling in CSS allows you to customize the appearance of the text on your web pages. You can change the font family (like Arial or Times New Roman), the size of the text, its color, how it’s aligned, and much more. This is crucial for creating visually appealing and readable websites.
Basic Font and Color Example
Let’s start with a simple example showing how to change the font and text color.
<!DOCTYPE html>
<html>
<head>
<title>Text and Font Example</title>
<style>
p {
font-family: Arial, sans-serif; /* Specifies the font family */
color: #333; /* Sets the text color to a dark gray */
}
</style>
</head>
<body>
<p>This is some example text styled with CSS.</p>
</body>
</html>Explanation:
font-family: Arial, sans-serif;: This line tells the browser to use the Arial font. If Arial isn’t available, it will use a generic sans-serif font. The comma-separated values allow for fallback fonts.color: #333;: This sets the text color to a dark gray using a hexadecimal color code.
Practical Usage: Headings and Font Sizes
Here’s an example showing how to style headings and change font sizes to improve readability and visual hierarchy.
<!DOCTYPE html>
<html>
<head>
<title>Headings Example</title>
<style>
h1 {
font-size: 2.5em; /* Larger font size for the main heading */
color: navy;
}
h2 {
font-size: 1.5em; /* Medium font size for subheadings */
color: darkgreen;
}
p {
font-size: 1em; /* Default font size for paragraphs */
line-height: 1.5; /* Improves readability by spacing out lines */
}
</style>
</head>
<body>
<h1>Welcome to My Website</h1>
<h2>About Us</h2>
<p>This is a paragraph about our website. We offer great services!</p>
</body>
</html>Explanation:
font-size: Controls the size of the text.emunits are relative to the parent element’s font size, making scaling easier.line-height: Adds space between the lines of text in a paragraph, making it easier to read. A value of 1.5 is common for good readability.- The different font sizes for
h1andh2create a clear visual hierarchy, making the content easier to scan.
Key Takeaways
- Use
font-familyto choose the font for your text. Include multiple fonts as fallbacks. - Use
colorto change the text color. You can use color names (likered), hexadecimal codes (like#FF0000), orrgb()values. - Use
font-sizeto control the size of your text.emandremunits are useful for responsive design. - Use
line-heightto improve readability by adjusting the spacing between lines of text.