78

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?

Russ Ferri
  • 6,459
  • 2
  • 22
  • 24
500
  • 6,509
  • 8
  • 46
  • 80

2 Answers2

148

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) {
    // ...
} 
Community
  • 1
  • 1
Russ Ferri
  • 6,459
  • 2
  • 22
  • 24
  • 3
    In case anyone else runs into this, the 'and' part must be all lowercase -- using AND (all caps) doesn't work. – cantera Aug 05 '13 at 00:19
  • Awesome! (here's an updated Sass documentation link - the one above didn't work for me: https://sass-lang.com/documentation/operators/boolean) – Sam Sverko Oct 17 '22 at 15:11
3

You can also do:

@if index("foo" "bar", $value) { .. }

Beware though:

  1. It might not be quite obvious what you are trying to do.
  2. It returns a number or null, not a boolean.