Defining Variable Variables using LESS CSS

前端 未结 5 1529
野趣味
野趣味 2020-11-28 06:21

Say I have three separate color schemes that are used on various pages in a site. Each color has a a light, medium and dark tint defined, and the color scheme is defined by

5条回答
  •  执念已碎
    2020-11-28 06:41

    Use interpolation and escaping, parentheses in the selector and parametric mixins to get the desired effect:

    • Dynamic variables by interpolation: In a string, "@{variable}" is replaced with the value of the variable. They can also be nested: Given @{@{var}-foo} and @var: bar;, the result is "barfoo".
      The resulting value is quoted. To remove these quotes, prefix ~.
    • Dynamic selectors by Selector interpolation: body.@{var} turns into body.bar.

    Example:

    @red-md:   #232;
    @red-dk:   #343;
    
    .setColor(@color) {
        body.@{color} { background-color: ~"@{@{color}-dk}";
            #container { background-color: ~"@{@{color}-md}";
             p { color: ~"@{@{color}-md}"; }
          }
        }
    }
    .setColor(~"red"); // Escape to prevent "red" turning "#FF0000"
    //.setColor(~"blue"); etc..
    

    Turns into:

    body.red {
      background-color: #334433;
    }
    body.red #container {
      background-color: #223322;
    }
    body.red #container p {
      color: #223322;
    }
    

    Note: When the answer was originally written, selector interpolation did not exist. See the previous revision for the solution if you're working with an old LESS compiler (before LESS 1.3.1a). Support for the old method will be dropped in LESS 1.4.0.

提交回复
热议问题