Hello world. Let's continue learning about SASS and how we can use conditionals in SASS.
In the previous article we learned about SASS Modules and how to use them. Let's have a look at how we can use flow control in SASS.
Introduction
SASS provides flow control through at-rules. These rules allow a user to decide what snippets of styling should be emitted. They can be combined with other features like mixins and functions to make writting and maintaining SASS code easier.
The following at-rules can be used to help change the way the code is emitted:
@if
,@else
&@else if
@each
@for
@while
Note about truthy and falsy values
false & null are considered false
Rest all values are considered truthy including 0, empty lists and empty strings
Conditionals
SASS conditionals include different decision making statements. They are as follows
@if
Rule@else
Rule@else if
Rule
@if
Rule
@if
rules written as @if <condition> { /* code block */ }
controls whether or not the styles are being emitted it or not. Upon the condition being true
the block is evaluated and styles are applied.
SCSS | CSS |
---|
|
|
@else
Rule
@else
rule is an optional rule that followes the @if
rule and is evaluated if the <condition>
returns false
SCSS | CSS |
---|
|
|
@else if
Rule
@else if
is used to define multiple conditional flows. This block is written between and @if
block and @else
block and is evaluated if the condition in the preceeding blocks return false.
SCSS | CSS |
---|
|
|
@each
Rule
@each
rule is used to loop through values such as lists
and maps
wherein it evaluates each element of the list/map. It is handy when there is a repetitive set of styles to be emitted
SCSS | CSS |
---|
|
|
@for
Rule
@for
works like a simple for loop counting up or down from one number to another.
@for
andto
indicate counting excluding the final number@for
andthrough
indicate counting including the final number
Creating a 12 column grid system using for loop
SCSS | CSS |
---|
|
|
@while
Rule
@while
loops works by continually executing the block as long as the condition remains true. Once the condition is evaluated as false the loop is exited.
SCSS | CSS |
---|
|
|
Conclusion
We've learnt how flow control can be used to generate and emit styles. Taking advantage of flow control, allows creating reusable classes and even more advanced concepts like themes. This series of articles have introduced the various concepts of SCSS and why SCSS is advantageous over CSS. Using these concepts one should explore building different ideas and even design systems.