Xavier Rubio Jansana

Xavier Rubio Jansana

Mobile engineer.
Android and iOS.
Scuba diver.

© 2024

Generating Repetitive CSS with Loops in LESS

Less is an amazing tool for simplifying your CSS: allows you to “extend” selectors (i.e. put selectors inside other selectors), to use mixins (i.e. a kind of “functions” that allow repeating optionally parametrized sets of CSS rules) and to use variables.

One missing feature is not having loops, for example to create a repetitive rule. Luckily enough, the language is powerful enough and there are smart people capable of taking advantage of that.

In this article I found the solution, which boils down to this:

// variables
@num-tiles-in-suit: 9;

// mixin with a guard to create a series of bamboo tiles
.makeTiles(@i) when (@i > 0) {
    @tile-value: @i - 1;
    // create the current tile rule
    .tile-@{tile-value} {
        background-image: url('/img/tiles/bamboo_@{i}.png');
    }

    // next iteration
    .makeTiles((@i - 1));
}

// create bamboo tiles numbered 0-8
.makeTiles(@num-tiles-in-suit);

Finally, I also found this other article, which didn’t work, probably because it was written for an older version of Less (the article is almost two years old).