What is CSS Nesting? CSS Nesting allows us to write CSS rules within other rules. This makes our code clearer and easier to maintain. This feature, which was previously only available through preprocessors like SASS or LESS, is now part of the official CSS specification. This means that we can now carry out a deeper and more intuitive nesting of CSS rules directly in our stylesheets.
Example:
Without nesting:
1.navbar {
2/* Style for the navigation bar */
3}
4
5.navbar .navbar-link {
6/* Style for links in the navigation bar */
7}
8
9.navbar .navbar-link:hover {
10/* Style for links on hover */
11}
With Nesting:
1.navbar {
2/* Style for the navigation bar */
3
4 > .navbar-link {
5 /* Style for links */
6
7 &:hover {
8 /* Style for links on hover */
9 }
10 }
11}
Why is this cool?
Clarity: Everything that belongs to an element stays together.
Maintainability: Changes are easier, as the structure is clearer.
Less writing: Less repetition of selectors.
Notes:
Browser support varies. Check the compatibility for your projects.
Use this function with care. Too deep nesting can also become unclear.
Further readings: