SASS | @if and @else
@if, @else, @else-if allows us to control flow in SASS file compilation like JavaScript.
-
@if: @if block will be compiled if the value of the conditional expression is true.
Syntax:
@if <conditional_expression> { ... }Example 1: SASS file
@mixin button-format( $round-button, $size ) { color: white; background-color: blue; width: $size; @if $round-button { height: $size; border-radius: $size / 2; } } .mybutton{ @include button-format(false, 100px); }Example 1: Compiled CSS file
.mybutton { color: white; background-color: blue; width: 100px; }Example 2: SASS file
@mixin button-format( $round-button, $size ) { color: white; background-color: blue; width: $size; @if $round-button { height: $size; border-radius: $size / 2; } } .mybutton{ @include button-format(true, 100px); }Example 2: Compiled CSS file
.mybutton { color: white; background-color: blue; width: 100px; height: 100px; border-radius: 50px; } -
@else: If the values of conditional expressions of all the above @if or @else-if blocks are false, then this block will be compiled.
Syntax:
@else { ... }SASS file:
@mixin theme ($theme-decide, $r, $g, $b) { // light background @if $theme-decide { background-color: rgba($r, $g, $b, 0.5); } // dark background @else { background-color: rgba($r, $g, $b, 1); // red color } } .myblock { @include theme(false, 255, 0, 0); }Compiled CSS file:
.myblock { background-color: red; // if true value is passed then rgba(255, 0, 0, 0.5); } -
@else if: The first @else-if block with conditional expression value true will be compiled. If no @else-if block expression evaluates to true then @else block will be compiled.
Syntax:
@else if <conditional_expression> { ... }SASS file:
@mixin theme ($theme-decide, $r, $g, $b) { // light background @if $theme-decide == 1 { background-color: rgba($r, $g, $b, 0.5); } // medium-dark background @else if $theme-decide == 2 { background-color: rgba($r, $g, $b, 0.7); } // dark background @else { background-color: rgba($r, $g, $b, 1); } } .myblock { @include theme(2, 0, 255, 0); }Compiled CSS file:
.myblock { background-color: rgba(0, 255, 0, 0.7); }
Recommended Posts:
- SASS | Nesting
- SASS | Interpolation
- SASS | @import
- CSS Preprocessor | SASS
- SASS | Comments
- SASS | Variables
- What is the difference between SCSS and SASS ?
- SASS | @mixin and @include
- SASS | Parent Selector
- SASS | Placeholder Selectors
- SASS | Shadowing and Flow Control
- SASS | Booleans and Boolean operators
- Last-child and last-of-type selector in SASS
- How to remove CSS “top” and “left” attribute with jQuery ?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

