CSS: nesting syntax
What is CSS nesting syntax
- CSS nesting is convenient syntax to let you nest CSS code, so the rules are grouped together for easier understanding and management.
- The nested code can always be written in a non-nested form. Nesting does not add anything new to CSS other than syntax.
Basic Nesting Example
/* nested syntax */ .card { background-color: pink; h2 { color: red; } p { color: blue; } } /* is equivalent to */ .card { background-color: pink; } .card h2 { color: red; } .card p { color: blue; }
Nesting syntax
by default, the relation of parent selector and its children have the same meaning as descendant selector.
.aa { .bb { color: red; } } /* is converted by CSS compiler to */ .aa .bb { color: red; }
you can override the relation
by prepending the combinator operator to the child selector, such as
>,
+,
~
.
.aa { > .bb { color: red; } } /* is converted by CSS compiler to */ .aa > .bb { color: red; }
nesting selector (ampersand &)
nested media query
browser support
supported by all major browsers since 2024.
It was introduced in 2019.