CSS Grouping Selectors
Grouping selectors share one declaration block between several selectors. A comma separates the selectors in a group.
One rule for two headings
The group h1, h2 shares one block. Both headings turn blue.
h1, h2 {
color: blue;
}A mixed group
A group can mix selector kinds. An element, a class, and an id share this block.
h1, .intro, #demo {
color: green;
}Every element at once
The * selector reaches every element. A list item and the button both turn red here.
* {
color: red;
}Example
h1, h2 {
color: blue;
}
p, li {
color: green;
}Key points
- Group: several selectors that share one declaration block
- A comma separates the selectors in a group.
- Grouping is shorthand for writing the same rule once per selector.
- Use a group when several selectors need the same declarations.
- * reaches every element, including html and body.
In this example, the first group colours both headings blue. The second group shares one block between p and li. Every paragraph and every list item turns green. Two grouped rules do the work of four separate rules.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does a comma between two selectors do?