-
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. The selector is then build during the compile time. This feature is called selector interpolation and cuts down on repetition a bit. It is especially useful in combination with mixins and nesting. Mixin parameter can be used to build its nested ruleset selector, so you can use mixins 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 keep their original form, but shorthand colors are converted into their hex values:
@hexColor: #ff00ff;
@shorthandColor: #f0f;
@namedColor: green;
Color @{hexColor} @{namedColor} @{shorthandColor} {
margin: 2 2 2 2;
}
compiles into:
Color #ff00ff green #ff00ff {
margin: 2 2 2 2;
}
Selector interpolation is especially useful in combination with mixins and nesting. 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;
}