Search code examples
csslessless-mixins

Generation CSS group via less


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
}

Solution

  • 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.