In the previous lesson, Data types in Sass, we learned Sass data types. To use them
efficiently, we're going to introduce loops and
@media in today's Sass tutorial.

Let's hope it'll be added to regular CSS some day! As well as other
preprocessor features.

Each

Each, written using the @each
keyword, is a loop that takes values from a list or a
map. We don't need to know the number of iterations of this
loop - it'll simply go through all the items. Let's show how to declare the
loop:

The $values variable contains a list or a map from which we
take the values. The $value variable is an individual value of each
item.

@each $valuein $values {
... code ...
}

Exercise #1

We need to create hover styles for different social network links. Let's
create a map of five different social networks which will contain the
social networks' names as keys and colors as values.
We'll use the each loop to create classes which we can assign to the links.

While

While, written using the @while keyword, is a
loop that is running while a condition is true. The loop has to
have such a condition which will make the loop stop sooner or later. This is how
we declare the loop:

@while [condition] {
... code ....
}

For

For, written using the @for keyword, is a loop
used for work with a predefined number of iterations. The loop uses a
control variable to which we define the
initial value and the final value. We can
count from the initial value to the final value exclusively (the
to keyword) or inclusively (the
through keyword).

@for $ifrom $intial [to/through] $final {
... code ...
}

Exercise #2

Let's create simple columns for a 12-column grid. In our solution, only width
will be calculated.

First, we'll create a $grid-count variable and
store the number of columns in it - 12 in this case. In the loop, we'll create a
class named .column-[number] to which we'll set
the calculated width of the column.

@media

Everyone surely knows CSS3 @media queries. In Sass, they
have the same functionality which is styling elements based on the screen size.
In Sass, @media is much easier to use since it supports
nesting.

Exercise #3

We'll change the background color of paragraphs, center them and change their
widths to 50%. We'll set the background color to blue for paragraphs wider than
500px and yellow for the rest. Of course, we won't use @media
twice, but only once and smartly.