Usage of loops is an excellent way to keep the code DRY and avoid repetition. Unlike in Sass, there are no built-in @for
or @each
directive in Less for writing loops but it can still be written using recursive mixins. A recursive mixin is nothing but a mixin which keeps calling itself.
There are four key components to a loop written using Less and they are as follows:
for([initialization]; [condition]; [final-expression])
), the guard is the [condition]
.[initialization]
as it sets the base value for the counter-like variable.[final-expression]
along with the next call.statement
in a typical for loop syntax.Below is a simple for loop written in Less that creates multiple #img*
selectors (where * is a number) and also sets the background-image
property as image*.png
.
.for-loop(@index) when (@index > 0) { /* recursive mixin with guard expression - condition */
/* the statement */
#img@{index} {
background-image: url("http://mysite.com/image@{index}.png");
}
/* end of the statement */
.for-loop(@index - 1); /* the next iteration's call - final-expression*/
}
.for-loop(3); /* the primary call - initialization */
Compiled CSS:
#img3 {
background-image: url("http://mysite.com/image3.png");
}
#img2 {
background-image: url("http://mysite.com/image2.png");
}
#img1 {
background-image: url("http://mysite.com/image1.png");
}