Contact!

@If, @Else, @Else if and @If not: Sass conditional statements

Conditional statements in Sass

We can use conditional statements in Sass in the form of @if, @else, @else if and @if not. Much like other programming languages this will write a CSS statement only if the condition is met. They are really useful statements to use in loops and mixins where we are likely to want to check whether a condition evaluates to true or false.

@if, @else and @else if

We open our conditional with @if and can follow it with @else if or @else. When a condition gets met then the css gets generated:

@if $something {
    // do something
} @else if $something-else {
    // do something else
} @else {
    // or do this
}

In Sass ‘null’ and ‘false’ are false; everything else is true

In my last post we looked at loops in Sass, so lets use the theme loop in our example.

$themeColours: (
    "pink": #DC51AC,
    "red": #D64651,
    "orange": #E55937,
);

@each $themeColour, $i in $themeColours {
    body {
        &.#{$themeColour} {
            background-color: $i;

            @if $themeColour == "pink" {
                color: #000;
            } @else if $themeColour == "red" {
                color: #fff;
            } @else {
                color: #DEEDEE;
            }
        }	
    }
}

Here we are looping through an array of theme colours to change the body text colour. We are using an if statement to check the key ($themeColour) for the values “pink” and “red” and otherwise setting a default colour. The output looks like this:

/* Output */

body.pink {
    background-color: #DC51AC;
    color: #000; 
}

body.red {
    background-color: #D64651;
    color: #fff; 
}

body.orange {
    background-color: #E55937;
    color: #DEEDEE; 
}

@if not

You can also evaluate for false by using @if not. For @if not to work you have to put parenthesis around the argument:

$width: 50px;

div {
    width: $width;

    @if not ($width == 100px) {
        background: red;
    } else {
        background: blue;
    }
}

This statement sets the background to ‘red’ if $width is not equal to 100px and to ‘blue’ if $width is equal to 100px.

/* Output */

div {
    width: 99px;
    background: red;
}

Join the discussion!

You might like: