Guards
Less has no @if like Sass. Instead the condition is written right in the mixin declaration after the word when — this is a guard. The mixin applies only if the condition is true. This lets styles be chosen by the argument value: a light background gets dark text, a dark background gets light text.
A condition on a mixin
Describe two variants of a mixin for text on a coloured background in styles/mixins.less:
// styles/mixins.less
.text-on(@background) when (lightness(@background) >= 50%) {
color: #111827;
}
.text-on(@background) when (lightness(@background) < 50%) {
color: white;
}lightness() returns the lightness of a colour in percent. Use the mixin for buttons:
// styles/components/buttons.less
.btn-warning {
background: #facc15;
.text-on(#facc15);
}
.btn-dark {
background: #111827;
.text-on(#111827);
}// styles/main.less
@import "mixins";
@import "components/buttons";.btn-warning {
background: #facc15;
color: #111827;
}
.btn-dark {
background: #111827;
color: white;
}<style>
.btn-warning {
background: #facc15;
color: #111827;
}
.btn-dark {
background: #111827;
color: white;
}
</style>
<button class="btn-warning">Edit</button>
<button class="btn-dark">Publish</button>Operators
| Notation | Meaning |
|---|---|
>, >=, <, =< | Greater, greater or equal, less, less or equal (<= works too) |
= | Equal |
when (A) and (B) | Both conditions |
when (A), (B) | At least one condition |
when not (A) | The condition is false |
Type checks
Type-checking functions answer true or false: iscolor(), isnumber(), isstring(), iskeyword(), isurl(), and for units ispixel(), ispercentage(), isem() and isunit(@value, rem). With them a mixin accepts different kinds of arguments, and default() fires when no other variant fits:
// styles/main.less
.border(@value) when (iscolor(@value)) {
border: 1px solid @value;
}
.border(@value) when (ispixel(@value)) {
border: @value solid #d1d5db;
}
.border(@value) when (default()) {
border: none;
}
.card {
.border(#2563eb);
}
.panel {
.border(2px);
}
.plain {
.border(off);
}.card {
border: 1px solid #2563eb;
}
.panel {
border: 2px solid #d1d5db;
}
.plain {
border: none;
}A condition on an ordinary rule
when can also follow a selector — then the whole rule is output only if the condition is true. This is how parts of a library are switched on and off:
// styles/main.less
@enable-shadows: true;
.card when (@enable-shadows = true) {
box-shadow: 0 2px 8px #d1d5db;
}.card {
box-shadow: 0 2px 8px #d1d5db;
}Change the value to false and the .card rule disappears from the CSS.
Common mistake
Out of JavaScript habit you may want to write "not equal" as !=. Less has no such operator:
// styles/main.less
@theme: dark;
.page when (@theme != light) {
background: #111827;
}Compilation fails with SyntaxError: expected condition. Write the negation as a word: when not (@theme = light).