Grouping Selectors and Selector Lists
What you'll learn: How to apply the same CSS styles to multiple selectors at once using commas, making your code more efficient and maintainable.
The Core Idea
Instead of writing the same styles over and over for different elements, you can group selectors together using commas. This creates a "selector list" where all listed selectors receive identical styles in one rule.
Think of it like a group email: instead of sending the same message individually to five people, you put all five addresses in the "To:" field at once.
Without Grouping (Repetitive)
h1 {
color: navy;
font-weight: bold;
}
h2 {
color: navy;
font-weight: bold;
}
.page-title {
color: navy;
font-weight: bold;
}
With Grouping (Efficient)
h1, h2, .page-title {
color: navy;
font-weight: bold;
}
Both approaches produce the same result, but the grouped version is cleaner and easier to maintain. If you later decide to change the color to dark blue, you only update one place instead of three.
When to Use Grouping
- Elements that share common base styles (like all headings needing the same font family)
- Multiple classes that need identical properties
- Combining type selectors, class selectors, and ID selectors that share styling
Formatting Tip
For better readability, especially with many selectors, write them vertically:
h1,
h2,
h3,
.page-title,
#main-heading {
color: navy;
}
Key Takeaway: Use commas to group multiple selectors into a single rule when they share the same styles—this reduces repetition, makes your CSS more maintainable, and keeps your stylesheets DRY (Don't Repeat Yourself).