In this blog post, we’ll explore grouping in CSS, a powerful technique to apply the same styles to multiple selectors like headers, classes, and IDs. Grouping helps reduce redundancy and keeps your CSS clean. We’ll also learn how to style one of the grouped elements differently by creating a new class or ID.
HTML Structure
Here’s the HTML structure for this lesson. Don’t forget to link the CSS file!
<!DOCTYPE html>
<html>
<head>
<title>Grouping in CSS</title>
<link rel="stylesheet" href="styles.css"> <!-- Link to your CSS file -->
</head>
<body>
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<p class="text">This is a paragraph.</p>
<p id="special-text">This is a special paragraph.</p>
</body>
</html>
Grouping Selectors
You can group selectors by separating them with commas. For example, in your styles.css file:
h1, h2, .text {
color: blue;
font-size: 18px;
}
This applies the same styles to <h1>, <h2>, and elements with the class .text.
Styling One Element Differently
To style the #special-text paragraph differently, create a new rule in your CSS file:
#special-text {
color: red;
font-weight: bold;
}
Now, the special paragraph stands out while the rest share the grouped styles.
Final Output
Here’s how your styles.css file should look:
h1, h2, .text {
color: blue;
font-size: 18px;
}
#special-text {
color: red;
font-weight: bold;
}
Grouping selectors saves time and makes your CSS more efficient. Try it out in your next project!
'Web Development Basics (CSS, JavaScript,' 카테고리의 다른 글
CSS_003_Understanding Descendant and Child Selectors in C (0) | 2025.01.26 |
---|---|
CSS_002_Styling Borders and Backgrounds with HTML and CSS (2) | 2025.01.12 |
CSS_001_Styling Basics with HTML and CSS (1) | 2025.01.08 |