Thomas McDevitt

scss – what’s the correct level of nesting?

One of the huge advantages of SCSS over plain CSS is that selectors can be nested in each other. This is to keep both the stylesheets and the markup neater and also keeps larger stylesheets easier to work with in the long run. However, it can sometimes be a mixed blessing if not used properly.

when nesting works well…

Check out this simple example. An unordered list is pretty much always going to have list items and these particular list items are always going to fall under this parent so nesting the selectors in this way is sensible.

Laying out the selectors in this way saves us from needing to add a new class to each of the list items which creates clutter in the mark up and makes it a little less obvious what’s going on in the SCSS. This approach also gives us license to use generic, easy-to-come-up-with class names for certain elements within (for this example, the selector .emphasize could be reused elsewhere) as long as they are sufficiently namespaced somewhere in the tree.

when nesting isn’t so great…

That’s not to say that all nested elements will invariably work like this. Often it’s tempting to nest selectors just because their elements are nested in the mark up too. This doesn’t, however, always make it the best approach. Consider this example…

Looks reasonable at a first glance, right? For the most part, it is — but let’s try moving the goal posts just slightly. Pretend that you get told that the menu bar would look much better at the bottom of the page. In theory, it’s just a matter of cutting out the relevant elements and dropping them in the correct place. In practise, the system falls apart when this is done.

Here, the elements that have been moved are no longer being styled correctly (the menu selectors were too specific and the footer selectors are not specific enough). The initial design assumes that they will be held in the header and debugging this regression could take a very long time for a larger system when the assumption was not necessary in the first place.

so ultimately…

Excessively specific CSS selectors are something to consider in both SCSS/sass and CSS alike. The issue that gets introduced with SCSS nesting is that it becomes much easier to end up with huge selectors which just means we have to be wary of what we’ll end up with in the chosen structure.

As with many things, there is a balance to be struck which will vary depending on the developer and the project at hand. Let us know of your experiences!

If you enjoyed the read, drop us a comment below or share the article, follow us on Twitter or subscribe to our #MetaBeers newsletter. Before you go, grab a PDF of the article, and let us know if it’s time we worked together.

blog comments powered by Disqus