Writing a loop for CSS using LESS

Note: I use the PHP compiler for LESS, so the available options/syntax isn’t completely the same as the regular version.

Writing a loop using LESS is actually really easy. All you need is a guarded mixin. For example, I use loops when I have a list of icons that all differ but it’s too much to manually write out each reference individually.

Say that I have a bunch of icons, and I’ve put them in my images folder and labelled them icon-1.png, icon-2.png etc. up until 10. If I want to add a class for each specific icon I could write the CSS out manually, but it would be easier to use a loop do write it for me. (This is a very simple example, you can also use less to calculate the positioning on sprite images or do another positioning that you want).

The LESS

.makeIcons(@i) when (@i > 0){
  (~"[email protected]{i}"){
    background: url('images/[email protected]{i}.png');
  }

  .makeIcons((@i - 1));
}

.my-group {
  .makeIcons(10);
}

In a nutshell I create a mixin called makeIcons. This takes one parameter, a index (as I’ve numbered my icons). There is a guard that will only run when @i is greater than 0.

The mixin will add a CSS declaration .icon-I (where I is the current @i value) with the background set to my icon file.

The last thing it then does is call itself while decreasing the count of @i (this is important, you could end up looping infinitely if you miss this step).

Further down the page I make my call to the mixing inside my own class wrapper. I pass in 10 as I have 10 icon I want to write declarations for. However if I ever add more icons I can just change this call and be done with the CSS.

All of this will generate the following CSS:

.my-group .icon-10 {
  background: url('images/icon-10.png');
}
.my-group .icon-9 {
  background: url('images/icon-9.png');
}
.my-group .icon-8 {
  background: url('images/icon-8.png');
}
.my-group .icon-7 {
  background: url('images/icon-7.png');
}
.my-group .icon-6 {
  background: url('images/icon-6.png');
}
.my-group .icon-5 {
  background: url('images/icon-5.png');
}
.my-group .icon-4 {
  background: url('images/icon-4.png');
}
.my-group .icon-3 {
  background: url('images/icon-3.png');
}
.my-group .icon-2 {
  background: url('images/icon-2.png');
}
.my-group .icon-1 {
  background: url('images/icon-1.png');
}

Nothing special, but it saves my sanity from a lot of copy/pasting. See it in action here.

Specifically what you need to look into when making a loop is mixins, variables, expressions and guards.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s