LESS Nesting

One of the features of LESS is that you can avoid writing long selector names and use Nesting. LESS Nesting also has the advantage that you reflect the hierarchical DOM structure when constructing style rules.

In this tutorial I’ll tell you about the principles and practical uses of LESS Nesting.

LESS Nesting

When constructing selectors in CSS we regularly end up with repeating the parent selector. Below you can see an example of this:

In LESS we can avoid this repetition and use the code below to achieve the same thing:

As you can see we do not have the repeat the parent selector “article” here because we nest the style rule for the anchor (‘a’) and for the paragraph (‘p’) inside the style rule for the parent.

The LESS nesting of style rules also helps us visualize the hierarchical relationship between the elements. Writing it this way will take a little time to get used to. But when you do it will make it much easier to prevent mistakes when you need to make changes to the style rule for specific elements.

In this example for instance we immediately see the different positions in the hierarchy of the two different anchor elements: one is a direct child of the article element and the other is a descendant of the article element and a direct child of the paragraph inside the article element.

The use of tabbing when writing LESS nested style rules is not required. But as you will probably agree it makes it easier to recognize the structure and locate (the style rules for) specific elements.

Pseudo-classes and the & symbol

When you look at Bootstrap’s LESS files you will often see the ampersand (&) being used. Below you can see an example from the Bootstrap 3 “badges.less” file:

The & symbol is used in LESS nesting to concatenate a pseudo-class with a parent selector. In CSS the code above would be written as:

There are other possible uses of the &-combinator in LESS nesting. Since I haven’t seen it used like that in Bootstrap I’ll not discuss those possibilities here. If you are interested in this you can read more about this in the article about LESS language nesting written by Mária Jurčovičová.

To be complete I also mention a tool here that can be used to translate CSS rules into LESS nested rules. Go to CSS2LESS if you want to try it. It can only be used for nesting and not to extract LESS variables or create mixins. If your CSS rulesets contain more complex selectors the tool will not translate them correctly.

Add your comment