0fyu7a
Last Updated: March 29, 2017
·
1.743K
· dperrymorrow
37b092a324da25d53fd63d780692b174

Using loops in LESS

So youre using LESS as your CSS preprocessor. One of the best things about LESS is that you can do loops and build classes dynamically.

Example:

I wanted to make classes to make divs a percentage of their container in increments of 10. I could have written 10 classes, but this is much nicer and easier to maintain.

.mixin-loop (@index) when (@index > 0) {
  .per-@{index}0 {
    display: inline-block;
    width: @index * 10%;
  }
  .mixin-loop(@index - 1);
}
.mixin-loop (0) {}
.mixin-loop(10);

Outputs...

.per-100 {
  display: inline-block;
  width: 100%;
}
.per-90 {
  display: inline-block;
  width: 90%;
}
.per-80 {
  display: inline-block;
  width: 80%;
}
.per-70 {
  display: inline-block;
  width: 70%;
}
.per-60 {
  display: inline-block;
  width: 60%;
}
.per-50 {
  display: inline-block;
  width: 50%;
}
.per-40 {
  display: inline-block;
  width: 40%;
}
.per-30 {
  display: inline-block;
  width: 30%;
}
.per-20 {
  display: inline-block;
  width: 20%;
}
.per-10 {
  display: inline-block;
  width: 10%;
}

Happy pre-processing!

Say Thanks
Respond

1 Response
Add your response

28755

how can we get strings in place of those numbers, can we have an array of strings and append them to the .per class in the above example ?

9 months ago ·