Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

Defining Variable Variables using LESS CSS

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 a class in the body. Assume that the "red" color scheme is the default. Like this:

Color Definitions:

@red-lt:   #121;
@red-md:   #232;
@red-dk:   #343;
@green-lt: #454;
@green-md: #565;
@green-dk: #676;
@blue-lt:  #787;
@blue-md:  #898;
@blue-dk:  #909;

Basic Default Style Example

body { background-color: @red-dk;
  #container { background-color: @red-md;
     p { color: @red-dk; }
  }
}

Different Color Scheme Style Example

body.green { background-color: @green-dk;
  #container { background-color: @green-md;
     p { color: @green-dk; }
  }
}

I'd like to use variables so that I don't have to re-write all of the color variations for each scheme, so that I can just write something like this:

body.[color-var] { background-color: @[color-var]-dk;
  #container { background-color: @[color-var]-md;
     p { color: @[color-var]-dk; }
  }
}

…but I can't quite wrap my head around how to accomplish that. Help…?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...