SCSS/CSS nesting max levels
Introduction
Nesting styles allow for less code repetition and cleaner code that is easier to read and quicker to write. However, too many nested levels can make code more difficult to read and make selectors too specific to override.
Decision
Max 4 levels of nesting. This does not include pseudo-classes, pseudo-elements and media queries.
For example in Drupal node page it can be structured below:
- The first level is node/view class
- The second level is wrapper class
- The third level is field class
- The fourth level is children of field class
Code block example:
.node--type-blog.node--view-mode-featured { .node__content { margin-top: 1rem; margin-bottom: 1rem; } .field--name-field-image { border-right: 24px solid color(primary-3); box-sizing: border-box; background: $blue-gradient; height: 100%; img { max-blend-mode: multiply; filter: grayscale(100%); } @include breakpoint($m-break) { flex: 0 1 50%; max-width: 50%; } } }
Context
It is convenient to keep endlessly nesting CSS selectors but too many levels makes code hard to read and makes selectors too specific and hard to override.
Consequences
- Code that is easier to read.
- Styles that can be easier overridden when needed.
Exceptions
- Media queries
- Pseudo-classes
- Pseudo-elements
- Old projects that already have the over nested code in place.
Additional Resources
None