Minimizing Nesting When Using a Preprocessor in CSS

Overly long, highly specific selectors are often caused by nested rule sets. Both Sass and Less support nested rule set syntax, which is useful for grouping related styles and saving keystrokes. Take, for example, the following CSS:

article {

margin: 2em auto;

}

article p {

margin: 0 0 1em;

font-family: ‘Droid Serif’,’Liberation Serif’,serif;

}

In both Less and Sass, we can rewrite this to take advantage of nesting:

article {

margin: 2em auto;

p {

margin: 0 0 1em;

font-family: ‘Droid Serif’,’Liberation Serif’,serif;

}

}

This gives us a descendant selector, and the output will match the standard CSS above. It’s also possible to nest a rule set inside a nested rule set. Take a look at this example:

nav {

> ul {

height: 1em;

overflow: hidden;

position: relative;

&::after {

content: ‘ ‘;

display: block;

clear: both;

}

}

}

Here, we’ve nested styles for ::after inside a declaration block for uL , which itself is nested inside a nav declaration block. When compiled, we end up with the following CSS:

nav > ul {

height: 1em;

overflow: hidden;

position: relative;

}

nav > ul::after {

content: ‘ ‘;

display: block;

clear: both;

}

So far, so good. Our selectors aren’t terribly long or specific. Now let’s look at a more complex example of nesting:

article {

color: #222;

margin: 1em auto;

width: 80%;

&.news {

h1 {

color: #369;

font-size: 2em;

&[lang]{

font-style: italic;

}

}

}

}

That doesn’t seem too egregious, right? Our [Lang] selector is only four levels deep. Well, take a look at our compiled CSS output:

article {

color: #222;

margin: 1em auto;

width: 80%;

}

article.news h1 {

color: #369;

font-size: 2em;

}

article.news h1 [lang] {

font-style: italic;

}

Uh-oh! Now we have a couple of high-specificity selectors: article.news h1 and article.news hi[Lang] . They use more characters than necessary, and require longer and more specific selectors to override them. Mistakes like this can swell the size of our CSS when repeated across a codebase.

Neither Less nor Sass has a hard limit on how deeply rules can be nested. A good rule of thumb is to avoid nesting your rules by more than three levels. Less nesting results in lower specificity and CSS that’s easier to maintain.

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *