-1

Im having trouble with I think a pretty simple thing. I need to add CSS to a element if a less variable equals to 1. Its kind of a on/off switch. I tried a few tutorials on guards but i dont think i get it the right way. My code:

@switch = 1
#element() when (@switch = 1) {
color: red;
}
ronline
  • 1
  • 1
  • Does this answer your question? [How to use if statements in LESS](https://stackoverflow.com/questions/14910667/how-to-use-if-statements-in-less) – Marc Barbeau Jan 13 '20 at 23:35

3 Answers3

2

First, you declare a variable using @switch: <value>; Then you drop the () from the element and use & when (@switch = 1) condition inside the body of the selector.

@switch: 1;

#element {
    & when (@switch = 1) {
        color: red;
    }

}

Or you could use an inline if function like below:

#element {
  color: if((@switch = 1), red, blue);
}

The later is the same as a ternary operator in any other language, first parameter is the logical operator, second value you want if the condition is true and an else value.

Adrian
  • 8,271
  • 2
  • 26
  • 43
2

You are defining the variable incorrectly. You need to use the : and not =.

@switch: 1;
  #element when ( @switch = 1) {
     color: red;
}

Which compiles to:

#element {
  color: red;
}

If the condition is met.

disinfor
  • 10,865
  • 2
  • 33
  • 44
-2

Turned out i had an old LESS version. The first solution from this link helped: https://github.com/less/less-docs/blob/master/content/features/css-guards.md

ronline
  • 1
  • 1