Sass in the Real World: book 2 of 4

@each control directive

The @each directive iterates through a list of values (for more information on refer to the first book of the series and the chapter on "Core data types") and passes the values into a block of code for execution. A simple example of this type of directive looks something like this:

$fruits: apples bananas oranges pomegranates peaches;

@each $fruit in $fruits {
    .i-like-#{$fruit} {
        background-image: url('/images/#{$fruit}.jpg')
    }
}

You can also use the @each directive with maps. The @each directive in combination of maps, there is the ability to extract the key and its corresponding value. Here is an example:

$zoo: ("puma": black, "sea-slug": green, "egret": brown);

@each $animal, $color in $zoo {
    .#{$animal}-icon {
        background-color: $color;
    }
}

We will tackle more practical examples of these directives and working with lists and maps in the next few chapters.