Grouping and comma
Learn to group multiple selectors with a comma.
Grouping with a comma
When you want the same styles on several selectors, you group them with a comma. h1, h2, h3 { color: navy; } turns all three heading levels navy.
The comma reads as 'and': each selector is evaluated separately and they all share the same declaration block. This cuts repetition and keeps your stylesheet tidy.
Mix selector kinds
Grouping is not limited to selectors of the same kind. You can mix type, class, and id selectors freely. h1, .title, #slogan { font-weight: bold; } is a valid group.
Each selector is evaluated on its own; what they share is the resulting styles. This flexibility makes arranging real themes much easier.
Exercise Group three headings
Turn h1, h2 and h3 into a single comma-separated group and set font-family: serif. All three selectors must share the same declaration block.
Show example solution
/* group the headings */
h1, h2, h3 {
font-family: serif;
}
Test yourself
-
What does this grouping do?
h1, h2, h3 { color: navy; }- It turns only h1 navy
- It turns only the last h3 navy
- It raises an error; grouping with a comma is not allowed
- It turns h1, h2 and h3 all navy
Show answer
It turns h1, h2 and h3 all navy — Correct. The three comma-grouped selectors share the same declaration block.
-
Add the third heading to the group
h1, h2, ____ { font-family: serif; }Show answer
h1, h2, h3 { font-family: serif; } -
Match each selector list to its meaning
- h1, h2, h3
- Three heading types
- .btn, .link
- Two classes
- #header, #footer
- Two ids
- *
- All elements