frodeborli frodeborli - 13 days ago 5
Less Question

Conditional when in less-file

I am making a theme editor for WordPress, and would like to use less to build the CSS file.

I have put a string in a variable like this:

@banner-separation-style: 'thick_border';


Then I'm trying to use when() like this:

when (@banner-separation-style = 'thick_border') {
header {
... some style
}
... and some css selectors
}


I've also tried combinations without quoting the variable.

How do I properly create something similar to if-blocks with less?

Answer

Guards (when statement) can only be used along with a mixin or a CSS selector. We can't write a when statement without using one of those. So, either write it with a mixin like below:

@banner-separation-style: 'thick_border';
.border-styles() when (@banner-separation-style = 'thick_border') {
    header { border: 2px solid red; }
    nav { border: 2px solid green; }
}
.border-styles;

or directly with the CSS selector like below:

@banner-separation-style: 'thick_border';
header when (@banner-separation-style = 'thick_border') {
    border: 2px solid red;
}
nav when (@banner-separation-style = 'thick_border') {
    border: 2px solid green;
}

or atleast using an unnamed selector (&) like below:

@banner-separation-style: 'thick_border';
& when (@banner-separation-style = 'thick_border') {
  header { border: 2px solid red; }
  nav { border: 2px solid green; }
}

The first version (with mixin) is the one that I prefer because (a) you don't have to repeat the condition multiple times like in the CSS selector version and (b) giving the mixin a name makes it more readable than using an unnamed selector. It is just my choice and some other user could actually prefer the last because it doesn't need that extra mixin call statement.