Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use if statements in LESS

Tags:

less

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); } 
like image 733
nkint Avatar asked Feb 16 '13 13:02

nkint


People also ask

How do you reduce IF statements in Python?

Use If/Else Statements in One Line To simplify the code and reduce the number of lines in the conditional statements, you can use an inline if conditional statement. Consider the following concise code that performs the same with one line for each if/else conditional statement.

Why you should avoid if statements?

There is nothing wrong with using if-statements, but avoiding them can sometimes make the code a bit more readable to humans. This is definitely not a general rule as sometimes avoiding if-statements will make the code a lot less readable. You be the judge. Avoiding if-statements is not just about readability.

How do you write codes without if-else?

i.e. you could just as easily write bool isSmall = i < 10; - it's this that avoids the if statement, not the separate function. Code of the form if (test) { x = true; } else { x = false; } or if (test) { return true; } else { return false; } is always silly; just use x = test or return test .


1 Answers

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; } 
like image 142
Onur Yıldırım Avatar answered Oct 18 '22 13:10

Onur Yıldırım



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!