Mike Sheward Avatar

I’m Mike Sheward, a Web Developer from England, UK.
I enjoy tinkering and engineering things for the Web.

Sass quick tips for beginners - Nesting

14th April 2017

For beginners getting to grips with Sass, it can be overwhelming sometimes, theres so much extra functionality you get to use in your workflow for generating CSS now, taking advantage of Sass (and other CSS preprocessors) and using it to generate even more awesome CSS is obviously the common goal, but it can go wrong very quickly if your not careful.

In this series of articles, I’m going to outline a few short tips on what you can do to avoid digging a messy hole when using Sass.

If you're unsure what Sass is or how to use it, i’d highly recommend it trying it out for yourself. Take a look at the docs here: http://sass-lang.com/


So what are messy holes, and more importantly, how can you stop digging them?

I call them messy holes because they can be easy to miss at first, but overtime, you slowly end up digging deeper and deeper making them worse, becoming even more of a mess, hence the naming “digging messy holes”.


The nesting and large selectors "messy hole"

Easily one of the best things you get to learn and use in Sass, is nesting! The ability to nest selectors is so handy, usually making it quicker to write and find certain selectors. 

This handy feature in Sass is a very easy way to start digging a messy hole though, this happens without noticing too. One minute your happily taking advantage of this nesting feature, nesting away. Before you know it your selectors can get quite large, and in general just larger than they need to be. I get it, it’s very easy to get carried away when nesting in Sass. However, there are a few problems that you may end up with if not careful:

  • Selectors may be unnecessarily larger than they need to be
  • Deeply nested selectors can end up being too specific, which means in certain situations you also can’t reuse them with ease, without creating the accompanying (and usually overly complex) HTML.
  • CSS File size output increases.

So how are these issues solved? Quite simply in fact; The unwritten rule in Sass, is try not to nest more than four levels deep. This of course depends on the situation, as in some cases you might want to be a little more lenient - it is common when nesting lists that this grows slightly over four levels deep. Majority of the time though, no deeper than four levels when nesting. Pseudo-elements however, i’d say can skip this rule though, but that’s personal preference.

Being aware and trying to stick to this may seam like a small thing to do, it does contribute to a much bigger picture though. It solves one of the most common messy holes that can be dug in Sass. It forces you to think a little more about the structuring your selectors and it’s accompanying HTML. You’ll (hopefully) end up with more reusable styling and more maintainable code. So it’s a win win all round.