DEV Community

loading...

Day 15 of #100DaysOfCode!

Christian Falucho
Passionate about building websites and web applications that can be used by millions of people. I hope to build tools that can help people.
・2 min read

Today's progress

Worked on using @each to iterate through each item in a list or a map.

What I learned

Similar to JavaScript's forEach() method. SASS also has a feature to iterate through each item in a list or map. Making it easier and faster to assign values to a variable.

For instance, let's say we want to create several <div> elements with different background colors. One way we can solve this problem is using @each directive within SASS.

Here's the code example.

Variable List

 $bg-colors: (
    bg-color1: blue,
    bg-color2: black,
    bg-color3: red
  );
Enter fullscreen mode Exit fullscreen mode

We created a variable list called $bg-colors which stores three different background colors.

Now we want to iterate through the list or map and assign each key to a new variable.

We can do that by doing the following...

Iterating and assigning values to new variables

@each $key, $bg-color in $bg-colors:{
  .#{$bg-color}-background {background-color: $bg-colors}
}
Enter fullscreen mode Exit fullscreen mode

The @each allows us to loop through the list or map and the $key is needed to reference the keys.

Next we use the interpolation and wrap our values $bg-color to get the values from our map or list.

The output should be the following...

Compiled CSS

.blue-background {
  background-color: blue;
}

.black-background {
  background-color: black;
}

.red-background {
  background-color: red;
}
Enter fullscreen mode Exit fullscreen mode

In Conclusion

@each allows you to iterate through the keys in a list or map and get their values. This is a useful tool especially when having to assign multiple values to a large set of class names.

Discussion (0)