5

Is it able to create such a mixin which generate CSS group? I will explain what I mean below:

.fancymixin(@max, @prefix) {
     //content what I don't know how to code
}

.fancymixin(10, x);

It generates something like:

.x10, .x9, .x8, .x7, .x6, .x5, .x4, .x3, .x2, .x1 {
     //some fancy style I want to set
}
Harry
  • 87,580
  • 25
  • 202
  • 214
kspacja
  • 4,648
  • 11
  • 38
  • 41
  • Yes, you can use loops. But are you specifically looking for `.x1, .x2 {}` structure or are you ok with `.x1{} .x2{}` structure also? – Harry Aug 20 '14 at 11:54
  • I meant first version because I would like to generate smaller amount of code lines. – kspacja Aug 20 '14 at 12:12
  • Yea, sort of understood that when you mentioned *group* but just wanted to be sure. By the way, I hope you noted my comment in the answer also. There is a small catch with this approach. – Harry Aug 20 '14 at 12:13

1 Answers1

6

You can use a loop (created using a guarded mixin) with one base class like below. The base class has the common properties and can be extended as many times from within the loop as required.

The base class and extend is required to create the CSS in the form .x1, .x2, .x3{} format. If it can be as .x1{} .x2{}, then the base class and extend is not really required.

.x1{ //base class with all common props
  color: blue;
} 

.fancymixin(@max, @prefix) when (@max > 1) { // loop from 10 to 1
    .fancymixin(@max - 1, @prefix); // call the next iteration of the loop
    .@{prefix}@{max}:extend(.x1){}; // extend the properties of the x1 base class
}

.fancymixin(10, x);

Compiled CSS:

.x1,
.x2,
.x3,
.x4,
.x5,
.x6,
.x7,
.x8,
.x9,
.x10 {
  color: blue;
}

Note: The above approach would not work if we want to call the same mixin to create another loop (like .fancymixin(10, y)) to create a separate set of properties for the .y* group because we are always extending the .x1 class properties.

Harry
  • 87,580
  • 25
  • 202
  • 214
  • There is one problem with this method however. The `x1` base is a constant. So, if you say wanted `.fancymixin(10,y)` and require a separate set of properties for `y* {}` then the code in this answer won't work. I am working on improving it. – Harry Aug 20 '14 at 12:07
  • 1
    It seems like what I was mentioning in the above comment is not possible currently. This [GitHub thread](https://github.com/less/less.js/issues/1485) has a similar use-case. – Harry Aug 20 '14 at 13:30