How to create a LESS mixin loop

We have all done it at some point. At some point you had to create a bunch of CSS classes just to change a small value. For example for setting different font-sizes, margins or paddings. Using LESS as your CSS pre-processor you'll have a ton of time and your code you'll look cleaner. Here's how:

Mixin Loop

This is the LESS loop we'll use. Imagine you want to create different classes/values for margin-top. I want to be able to use classes called: .margin-top-1em, .margin-top-2em, and so on.

@iterations: 4; // Set up the number of times it will loop

.mixin-loop (@i) when (@i > 0) {

  // One class
  .margin-top-@{i}em {
    margin-top: (1em * @i);
  }

  // Another class
  .margin-bottom-@{i}em {
    margin-bottom: (1em * @i);
  }

  .mixin-loop(@i - 1);
}

.mixin-loop(@iterations);

Compiled CSS

Here's what it looks like once the LESS code is compiled:

.margin-top-4em {
  margin-top: 4em;
}

.margin-bottom-4em {
  margin-bottom: 4em;
}

.margin-top-3em {
  margin-top: 3em;
}

.margin-bottom-3em {
  margin-bottom: 3em;
}

.margin-top-2em {
  margin-top: 2em;
}

.margin-bottom-2em {
  margin-bottom: 2em;
}

.margin-top-1em {
  margin-top: 1em;
}

.margin-bottom-1em {
  margin-bottom: 1em;
}

Tip: always set compression/minify your output CSS when compiling LESS #perfmatters !

About Rick

Senior Front-end Software Engineer from Barcelona, Haidong Gumdo Instructor (korean martial art of the sword), street photographer, travel lover, TV addict, Boston Red Sox fan, and privacy advocate.

Leave a Reply

Add <code> Some Code </code> by using this tags.

*
*