LESS is a great tool for removing the tediousness out of CSS styling by allowing nested selectors and use of variables.
But there is much more to the language allowing for more complex logic to be embedded. One of the great features of the language is the ability to loop and create styles recursively.
A good practical use for this functionality is to style a comments section:
See the Pen Styling nested elements with LESS by Marcin Jackowiak (@marcinjackowiak) on CodePen.
Below is the basic LESS code will generate CSS that varies the div background color depending on how deep the element is in the DOM hierarchy.
It is a prime example of something that could be a nightmare to maintain directly in the CSS stylesheet.
#namespace { .test(@i,@x) { div { background-color: lighten(red, @i*(50/@x)); } } .recursive(@x; @i:0) when (@i <= @x) { .test(@i,@x); div { .recursive(@x; (@i+1)); } } } div { width: 200px; height: 200px; padding: 20px; border: 1px solid #888; } & { #namespace > .recursive(5); }
What it generates is a nice gradient of red that will lighten the deeper you go.
The following formula will lighten the color by 50% with each level. To create a smoother transition simply lower the
number.
background-color: lighten(red, @i*(50/@x));
The argument in the .recursive mixin allows you to specify the depth to which the styles will be generated.
& { #namespace > .recursive(5); }
The resulting CSS is as follows.
div { width: 200px; height: 200px; padding: 20px; border: 1px solid #888; } div { background-color: #ff0000; } div div { background-color: #ff3333; } div div div { background-color: #ff6666; } div div div div { background-color: #ff9999; } div div div div div { background-color: #ffcccc; } div div div div div div { background-color: #ffffff; }