CSS Grouping
and Nesting
Selectors
Grouping Selectors
In a stylesheet, there are many elements with the same styles.
h1 {
color: green;
}
h2 {
color: green;
}
p {
color: green;
}
To minimize code, you can use grouping selectors.
Each selector is separated by a comma.
In the following example, we use grouping selectors for the above code:
Example
h1, h2, p {
color: green;
}
Nesting Selectors
It may apply styles to selectors within selectors.
The following example sets four styles:
p { }
: Specifies a style for all p elements..marked { }
: Specifies a style for all elements with class="marked"..marked p { }
: Specifies a style for p elements within elements with class="marked".p.marked { }
: Specifies a style for p elements with class="marked".
Example
p {
color: blue;
text-align: center;
}
.marked {
background-color: red;
}
.marked p {
color: white;
}
p.marked {
text-decoration: underline;
}