Over a million developers have joined DZone.

Nesting in Less and Sass

DZone's Guide to

Nesting in Less and Sass

This article will give you a birds-eye-view on nesting (get it?) using these two well known and commonly used CSS pre-processors.

· Web Dev Zone ·
Free Resource


The code should be organized. That's a fact and I think is a very good one for the opening of an article about nesting.


For the best way to select the desired element, we should use selectors. However, CSS doesn't allow nesting, and every element must be selected separately. In other words, if there is a child element it should be defined completely separate from the parent.

Less and Sass

Less and Sass are CSS pre-processors which extend the CSS language in valuable ways. Just one of many improvements they offer is an easier and more natural way of defining nested elements and their relative position among themselves, nesting!

Nesting makes the code easy to read, extend, and maintain. It is an option which has the same interpretation in less and sass so the next explanation is universal for both of them.






.grandparent .parent1 .child1{} 
.grandparent .parent1 .child2{} 
.grandparent .parent1 .child3{} 
.grandparent .parent2 .child1{} 
.grandparent .parent2 .child2{} 

So, instead of the defining child elements with space in the same line (CSS syntax), pre-processors enable you to use the same structure as in HTML. So if the child3 element is a child of the parent1 and parent1 is a child of the grandparent, then you can define all these elements as shown above.


As a developer, I'm full of best practices and pieces of advice and here comes one of them. Nesting should must be used for pseudo-classes.

To define a specific state of an element, it is necessary to add a pseudo-class next to the selector and with nesting this is ultra-intuitive - just put an ampersand next to the pseudo-class. The & always refers to the parent selector when nesting. Besides this use, it can (but it's unnecessarily) be used next to the child selector but with _.








Deep nesting, which is actually recommended, has its downsides - it's hard to reuse, override and make CSS files bigger, but developers who use it are aware of these limitations and it's not a problem (believe me).



less/sass coding ,sass ,less ,web dev ,front-end development

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}