Using multiple conditions (AND) in SASS IF statement

500 picture 500 · Jun 21, 2013 · Viewed 52.3k times · Source

Using SASS, I would like to have multiple condition in IF statement

What I use right now :

@function color-x ($alpha) {
    @if      $accent == red   {@return red($alpha)} 
    @else if $accent == green {@return green($alpha)} 
    @else if $accent == blue  {@return blue($alpha)}
}

My naive (failed) attempt to use multiple conditions :

@function color-x ($alpha) {
    @if      $accent == red   && theme == light {@return red($alpha)} 
    @else if $accent == green && theme == light {@return green($alpha)} 
    @else if $accent == blue  && theme == light {@return blue($alpha)}
}

Is it possible to have multiple conditions?

Answer

Russ Ferri picture Russ Ferri · Jun 21, 2013

From the Sass language reference documentation:

Boolean Operations

SassScript supports and, or, and not operators for boolean values.

(link)

So an if statement expression with a compound condition would look like this:

@if $var1 == value1 and $var2 == value2 {
    // ...
}

Further, parentheses can be used to affect the order of operations in a more complicated expression:

@if ($var1 == value1 and not ($var2 == value2)) or ($var3 == value3) {
    // ...
}