Sass: @if and @else
@if
The @if
rule is written @if <expression> { ... }
, and it controls whether or not its block gets evaluated (including emitting any styles as CSS).
The expression usually returns either true
or false
. If the expression returns true
, the block is evaluated, and if the expression returns false
it’s not.
The .scss file below
@mixin avatar($size, $circle: false) {
width: $size;
height: $size;
@if $circle {
border-radius: $size / 2;
}
}
.square-av {
@include avatar(100px, $circle: false);
}
.circle-av {
@include avatar(100px, $circle: true);
}
and the .css below:
.banner {
background-color: #f2ece4;
color: #036;
}
body.dark .banner {
background-color: #6b717f;
color: #d2e1dd;
}
@else if
You can also choose whether to evaluate an @else
rule’s block by writing it @else if <expression> { ... }
.
The block is evaluated only if the preceding @if
‘s expression returns false
and the @else if
’s expression returns true
.
You can chain as many @else if
s as you want after an @if
.
The first block in the chain whose expression returns true
will be evaluated, and no others. If there’s a plain @else
at the end of the chain, its block will be evaluated if every other block fails.
The .scss below
@use "sass:math";
@mixin triangle($size, $color, $direction) {
height: 0;
width: 0;
border-color: transparent;
border-style: solid;
border-width: math.div($size, 2);
@if $direction == up {
border-bottom-color: $color;
} @else if $direction == right {
border-left-color: $color;
} @else if $direction == down {
border-top-color: $color;
} @else if $direction == left {
border-right-color: $color;
} @else {
@error "Unknown direction #{$direction}.";
}
}
.next {
@include triangle(5px, black, right);
}
and the .css below
.next {
height: 0;
width: 0;
border-color: transparent;
border-style: solid;
border-width: 2.5px;
border-left-color: black;
}