Lately I discovered LESS and started loving and using it. In combination with Twitter’s Bootstrap it become very easy to generate CSS in a very comfortable way.

At one point I needed to generate roughly 30 css classes to leverage CSS sprites. I’ve been used do this all by hand back when CSS was written without any help, but having such awesome tools like LESS there must be a way to do this more comfortable. After searching for a while various sources (and also the LESS documentation) said that there are no loops in LESS, so I looked through the Bootstrap sources I found some stuff that looked similar to loops (grid.less and mixins.less).

After simplifying what I found here is the shortest version of doing a loop-like construct in LESS:

LESS code:

@iterations: 30;

// helper class, will never show up in resulting css
// will be called as long the index is above 0
.loopingClass (@index) when (@index > 0) {

	// create the actual css selector, example will result in
	// .myclass_30, .myclass_28, .... , .myclass_1
	(~".myclass_@{index}") {
		// your resulting css
		my-property: -@index px;
	}

	// next iteration
	.loopingClass(@index - 1);
}

// end the loop when index is 0
.loopingClass (0) {}

// "call" the loopingClass the first time with highest value
.loopingClass (@iterations);

Resulting CSS:

.myclass_30 {
  my-property: -30 px;
}
.myclass_29 {
  my-property: -29 px;
}

.......
.......
.......

.myclass_1 {
  my-property: .1 px;
}

This is just a very basic example but I thing you get the idea how to use this trick.