Learning LESS: Nesting Rules

by . Originally posted

So you’ve managed to complete the simple LESS setup, written a few variable declarations, even used some of the built in functions to calculate new stylesheet colours… but you’re still writing line after line of code. Is there something in LESS to simplify the amount you’re writing?

Yes… thanks to nested rules!

Ever seen something like this before:

// Lots and lots of identical selectors...
div#nav { ... }
div#nav ul { ... }
div#nav ul li { ... }
div#nav ul li a { ... }
div#nav ul li.myStyle { ... }
div#nav label { ... } 

Without the actual CSS declarations specified, you can focus on the amount of duplication that we write on a regular basis. Not only that but it can be ugly and hard to see how the code hangs together.

Needless to say we also don’t normally write hierarchical selectors in the exact order they apply, so this example is probably a cleaner than your actual code.

That’s a lot of improvement we can do here.

// Nesting rules in LESS
div#nav {
    ...

    ul {
         ...

        li  {
            ...
            a { ... }
            &.myStyle { ... }
            }

        }

    label { ... }

} 

Now I’ll admit when I first saw the code laid out like this I wasn’t initially blown away, but once you start using it in your project it becomes one of those ‘how-did-we-survive-before’ features.

Nested descendants in LESS

One important thing to note in the above example is how myStyle was applied to the <li> element without being applied to all the <li> descendants. To do this I simply preceded the selector with the ampersand character (&), and this locks it to the current element.

Without this ‘descendant lock’ being applied, the selector would apply to all myStyle classed elements under the <li> element.

Obviously LESS doesn’t compile the code like this, it wouldn’t be valid CSS. In fact it’d compile back into my original example.

A nice and short article this week on LESS, but a mighty useful feature!

Categories: Computing, Programming

Tags: ,

Leave a Reply

Your email address will not be published.

Links and useful footery things…

Copyright © 2018 Paul Joyce. Follow me on Twitter or perhaps Google+