Control directives and expressions are used in SASS to include styles only under certain defined conditions.
As a feature, they’re quite advanced and are mainly useful in mixins. Common directives include @if
, @else
, @for
and @while
.
@if and @else
The @if
and @else
directives are similar to if
and else
statements in JavaScript.
@if
takes an expression and executes the styles contained within its block — if the evaluation is not false (or null).
@else
will then be checked, if the previous @if
evaluated to false.
For example:
@mixin heading($size) {
@if $size == large {
font-size: 4rem;
}
@else if $size == medium{
font-size: 3rem;
}
@else if $size == small {
font-size: 2rem;
}
@else {
font-size: 1rem;
}
}
.h1 {
@include heading(large);
}
.h6 {
@include heading(small);
}
Here, we are using a heading mixin which accepts $size
as an argument. We can have a different size for each of our headings depending on which value we pass to the mixin.
@for
You can use the @for
directive to execute a group of statements a specified number of times. Effectively this is a loop.
It has two variations. The first uses the through
keyword, it’ll execute the statements from start to end, inclusive.
An example using through
:
@for $i from 1 through 5 {
.list-#{$i} {
width: 2px * $i;
}
}
This will produce the following CSS output:
.list-1 {
width: 2px;
}
.list-2 {
width: 4px;
}
.list-3 {
width: 6px;
}
.list-4 {
width: 8px;
}
.list-5 {
width: 10px;
}
If we replace the through
keyword with to
, it makes the loop exclusive. The difference being that it won’t execute when the variable is equal to end.
An example using to
:
@for $i from 1 to 5 {
.list-#{$i} {
width: 2px * $i;
}
}
This produces the following CSS:
.list-1 {
width: 2px;
}
.list-2 {
width: 4px;
}
.list-3 {
width: 6px;
}
.list-4 {
width: 8px;
}
@while
We could instead implement the above code using the @while
directive. As its name implies, it will continue to output CSS produced by the statements while the condition returns true.
The syntax is as follows:
$i: 1;
@while $i < 6 {
.list-#{$i} {
width: 2px * $i;
}
$i: $i + 1;
}
The output is identical, so you could opt for your personal preference based on the syntax.
In the next article, we’ll look at SASS interpolation.
Conclusion
If you liked this blog post, follow me on Twitter where I post daily about Tech related things!
If you enjoyed this article & would like to leave a tip — click here