I don’t know when I’ve started using Sass but. My first blog post on that topic dates back to 2012. There are many features I love Sass for, and one of them is nesting.
What is nesting in Sass
A typical example for when nesting is really helpful is when dealing with CSS selectors of elements, that are usually children of other elements. Unordered lists used for navigation menus are a great example here:
nav {
ul {
list-style: none;
ul {
display: block;
}
}
li {
display: inline-block;
}
a {
display: block;
padding: 5px 10px;
}
}
In this code, we have some child (or grandchild) nodes of a <nav>
tag. By nesting them, and using a preprocessor like Sass, we get the following result in the compiled CSS:
nav ul {
list-style: none;
}
nav ul ul {
display: block;
}
nav li {
display: inline-block;
}
nav a {
display: block;
padding: 5px 10px;
}
Many of you will probably agree, that the Sass code is easier to write and change, as you don’t have to write the full CSS selector. Rearranging the nesting becomes really easy, compared to replacing the middle parts of long CSS selectors. The selectors I’ve chosen above are rather short. This is on purpose, as you should not nest too much, just because you can, or even worse, because it replicated your HTML. We probably don’t need a CSS selector like “nav ul li a
“, since if we just want to style every link in the navigation, just having “nav a
” is all we need.
How to use nesting without a preprocessor?
If you try to use that nicely nested code in a .css
file, it might just work. No more need to use a preprocessor. But you might have to support a browser, that does not implement this new specification, and which doesn’t understand this syntax. For those browsers, all you have to do is adding an &
before each nested selector. The code above changes to this:
nav {
& ul {
list-style: none;
& ul {
display: block;
}
}
& li {
display: inline-block;
}
& a {
display: block;
padding: 5px 10px;
}
}
Fortunately, all major browsers have implemented this new specification, where you don’t have to add the &
before the nested selectors. But they also support the old syntax. So if you want to be safe, you could still use this old syntax for some time. I can also highly recommend reading a bit more on CSS nesting in the documentation.
Conclusion
That’s it! Just use nesting as in Sass, Less and other preprocessors and modern browsers will understand your code. If you still use a preprocessor for other things like variables, they will still convert this syntax into the normal “long CSS selectors”.
With CSS custom properties (variables) and nesting, there are two of three features now native to CSS, I use a lot in Sass. The last one is “templating” using multiple files for different part/components. The rest like mixins are more “nice to have” for me, but not really essential.