Nesting is a very powerful feature, but should be used with caution. It can happen quite easily and quickly, that you start nesting and carry on including all children in a nest, of a nest, of a nest. Let me demonstrate:
// SCSS
header {
// [css-rules]
.holder {
// [css-rules]
.dropdown-list {
// [css-rules]
ul {
// [css-rules]
li {
margin: 1rem 0 0 1rem;
}
}
}
}
}
// CSS output of the last rule
header .holder .dropdown-list ul li {
margin: 1rem 0 0 1rem;
}
The li
from the example above has a margin
set. Let's say we want to override this in a media-query later on.
@media (max-width: 480) {
// will not work
.dropdown-list ul li {
margin: 0;
}
// will work
header .holder .dropdown-list ul li {
margin: 0;
}
}
So by nesting too deep consequently you'll have to nest deep again whenever you want to overwrite a certain value. Even worse, this is often where the rule !important
comes to use.
@media (max-width: 480) {
// BIG NO-NO, don't do this
.dropdown-list ul li {
margin: 0 !important;
}
Why is the !important
-rule is a bad idea
You should write your SCSS in a good fashion that these workarounds aren't even necessary in the first place. Using !important
on such a minor issue already will lead you down a rabbit hole!
This is fairly similar to the specificity problem, but worth pointing out separately. If you style something like a button or even a dropdown, you might want to reuse those styles somewhere else on your page.
By nesting too deeply your styles are only bound to the elements sitting inside the most outer parent (the element at the top of your SCSS). This leads you to copy styles and paste them somewhere else again. Possibly in an other nested rule.
Your stylesheets will become larger and larger and more difficult to maintain.
Most styleguides set the maximum depth to 2. This is good advice in general, as there are only very few occasions where you'd want to nest deeper. Most of the time, 2 is enough.