-
Notifications
You must be signed in to change notification settings - Fork 47
Less Language Selector Interpolation
The selector can reference any variable available in its scope. This feature is called selector interpolation. The selector is the build during the compile time.
Selector interpolation cuts down on repetition a bit and is especially useful in combination with mixins. As mixins parameter can be placed into its nested ruleset selector, mixin can be used to add almost any kind of dynamically built selectors into their callers.
Note: interpolated selectors can not be used as mixins.
Variable name must be placed inside curly braces preceded by at symbol @{variable}
. You can use variable as a part of element name, class name, id and as a pseudo class parameter. Putting it into any other place is not legal.
Valid placements example:
@headingLevel: 3;
@headingPosition: 1;
@id: 42;
h@{headingLevel}:nth-child(@{headingPosition}), #id-@{id}, .class-name-@{id} {
color: red;
}
Compiled result:
h3:nth-child(1), #id-42, .class-name-42 {
color: red;
}
If the variable contains string, then the whole string is placed into selector - including its quotation marks.
Sample less:
@singleQuoteString: 'string';
@doubleQuoteString: "string";
@{singleQuoteString} @{doubleQuoteString} {
margin: 2 2 2 2;
}
compiles into:
'string' "string" {
margin: 2 2 2 2;
}
Workaround: use values escaping if you need a string but not its quotation marks:
@escapedVariable: ~"h1";
@{escapedVariable} {
margin: 2 2 2 2;
}
compiles into:
h1 {
margin: 2 2 2 2;
}
Named colors are converted into their hex values:
@hexColor: #ff00ff;
@namedColor: green;
Color @{hexColor} @{namedColor} {
margin: 2 2 2 2;
}
compiles into:
Color #ff00ff #008000 {
margin: 2 2 2 2;
}
Selector interpolation is especially useful in combination with mixins. Mixin can add almost any kind of dynamically built selectors into its caller:
.mixin(@className) {
.@{className} {
padding: 2 2 2 2;
}
}
pre {
.mixin(~"java")
}
compiles into:
pre .java {
padding: 2 2 2 2;
}
Selector interpolation is supported only inside element names, class names, ids and as a pseudo class parameters. Their usage anywhere else is illegal.
Illegal selector interpolation, causes compile error:
@pseudoClass: ~"nth-child";
//illegal selector
h3:@pseudoClass(2) {
color: red;
}
//another illegal selector
@variable: "text";
h1[text=@{variable}] {
padding: 2 2 2 2;
}
If anyone ever needs it, this limitation has a simple workaround. Just place the whole "illegal" part into an escaped variable:
@pseudoClass: ~"nth-child";
//workaround
@fullPseudo: ~":@{pseudoClass}(2)";
h3@{fullPseudo} {
color: red;
}
//workaround
@variable: "content";
@attribute: ~'[text="@{variable}"]';
h1@{attribute} {
padding: 2 2 2 2;
}
compiles into:
h3:nth-child(2) {
color: red;
}
h1[text="content"] {
padding: 2 2 2 2;
}