Functions and Operations
Functions and Operations
For Loops
For loops in Sass can be used to style numerous elements or
assigning properties all at once. They work like any for-loop you've
seen before.
Sass's for loop syntax is as follows:
@for $i from $begin through $end {
//some rules and or conditions
}
In the example above:
$i is just a variable for the index, or position of the element in
the list
$begin and $end are placeholders for the start and end points
of the loop.
The keywords through and to are interchangeable in Sass
For-loops are useful for many things, but in the following exercises
we will be using them to style a block of rainbow divs!
Conditionals
In Sass, if() is a function that can only branch one of two ways
based on a condition. You can use it inline, to assign the value of a
property:
width: if( $condition, $value-if-true, $value-if-false);
For cases with more than two outcomes, the @if, @else-if, and
@else directives allow for more flexibility.
@mixin deck($suit) {
@if($suit == hearts || $suit == spades){
color: blue;
}
@else-if($suit == clovers || $suit == diamonds){
color: red;
}
@else{
//some rule
}
}
The mixin above is a good example for how we would want to
handle the coloring of a deck of cards based on a suit condition.
Generalizations
Functions in Sass allow for an easier way to style pages,
work with colors, and iterate on DOM elements.
Having both for loops and each loops gives the programmer
different formats to iterate on both lists and maps.
The introduction of conditional statements allows you to
create logic-based styling rules using SCSS.
There are other native Sass functions available to use, and you can
even make your own custom functions if you have a good
foundation in Ruby, check out more information here.
Congrats! This lesson equipped you with new knowledge on some
of the most popular functions and operations available to you in
SCSS. Next, let's learn about the best practices for growing your
Sass codebase.