Dynamically define a variable in LESS CSS

前端 未结 4 965
独厮守ぢ
独厮守ぢ 2020-12-06 02:12

I am trying to create a mixin that dynamically defines variables in LESS CSS, by actually assigning them a composite name.

The simplified use-case (not the real one)

4条回答
  •  佛祖请我去吃肉
    2020-12-06 02:22

    I`m not really sure for what you want to use this, but one of my suggestion is based on @ScottS answer. On my real world, I need to create a web app, where it would show several brands and each brand have their own text color, background and so on... so I started to chase a way to accomplish this in LESS, what I could easily do on SASS and the result is below:

    LESS

    // Code from Seven Phase Max
    // ............................................................
    // .for
    .for(@i, @n) {.-each(@i)}
    .for(@n)     when (isnumber(@n)) {.for(1, @n)}
    .for(@i, @n) when not (@i = @n)  {
        .for((@i + (@n - @i) / abs(@n - @i)), @n);
    }
    
    // ............................................................
    // .for-each
    
    .for(@array)   when (default()) {.for-impl_(length(@array))}
    .for-impl_(@i) when (@i > 1)    {.for-impl_((@i - 1))}
    .for-impl_(@i)                  {.-each(extract(@array, @i))}
    
    
    // Brands
    @dodge : "dodge";
    @ford : "ford";
    @chev : "chev";
    
    // Colors
    @dodge-color : "#fff";
    @ford-color : "#000";
    @chev-color : "#ff0";
    
    // Setting variables and escaping than
    @brands: ~"dodge" ~"ford" ~"chev";
    
    // Define our variable   
    .define(@var) {
      @brand-color: '@{var}-color';
    }
    
    // Starting the mixin
    .color() {
        // Generating the loop to each brand
        .for(@brands); .-each(@name) {
            // After loop happens, it checks what brand is being called
            .define(@name);
             // When the brand is found, match the selector and color
            .brand-@{name} & {
                color: @@brand-color;
            }
        }
    }
    
    .carColor {
        .color();
    }
    

    Te result will be:

    CSS

    .brand-dodge .carColor {
        color: "#fff";
    }
    .brand-ford .carColor {
        color: "#000";
    }
    .brand-chev .carColor {
        color: "#ff0";
    }
    

    This is very tricky and I had to use several elements to get what I needed, first used a set of mixins provided by Seven Phase Max and you can find it here and than, the @ScottS answer was the piece that was missing fro my puzzle... hope this helps you and others that need to create a set of Variables to be part of another variable and create a more dynamic less file.

    You can copy my entire code and test at http://lesstester.com/

提交回复
热议问题