How to use if statements in LESS

nkint picture nkint · Feb 16, 2013 · Viewed 99.7k times · Source

I'm looking for some kind of if-statement to control the background-color of different div elements.

I have tried the below, but it doesn't compile

@debug: true;

header {
  background-color: (yellow) when (@debug = true);
  #title {
      background-color: (orange) when (@debug = true);
  }
}

article {
  background-color: (red) when (@debug = true);
}

Answer

Onur Yıldırım picture Onur Yıldırım · May 19, 2014

There is a way to use guards for individual (or multiple) attributes.

@debug: true;

header {
    /* guard for attribute */
    & when (@debug = true) {
        background-color: yellow;
    }
    /* guard for nested class */
    #title when (@debug = true) {
        background-color: orange;
    }
}

/* guard for class */
article when (@debug = true) {
    background-color: red;
}

/* and when debug is off: */
article when not (@debug = true) {
    background-color: green;
}

...and with Less 1.7; compiles to:

header {
    background-color: yellow;
}
header #title {
    background-color: orange;
}
article {
    background-color: red;
}