Dynamically define a variable in LESS CSS

前端 未结 4 964
独厮守ぢ
独厮守ぢ 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:30

    To follow up on the accepted answer you can also define a value for the variable by extending the .define() mixin as follows. This allows you to use a temporary set of variables within a rule.

    .define(@var, @val) {
      .foo() when (@var = temp1) {
        @temp1: @val;
      }
     .foo() when (@var = temp2) {
        @temp2: @val;
      }
     .foo() when (@var = temp3) {
        @temp3: @val;
      }
      .foo();
    }
    
    .define(temp2, 2);
    .test {
      .define(temp1, 0);
      prop: @temp1;
    }
    .test2 {
      prop: @temp2;
    }
    

    CSS Output

    .test {
      prop: 0;
    }
    .test2 {
      prop: 2;
    }
    

    Here is a more complicated gist of how I use this in a mixin for generating responsive background images with background-size: cover; (and an IE8 fallback).

提交回复
热议问题