I am trying to write a loop that will cycle through colors and condense the amount of code in my scss file. Here is a simple example of what I have:
$color1: blue;
$color2: red;
$color3: white;
$color4: black;
.color1-bg { background-color: $color1; }
.color2-bg { background-color: $color2; }
.color1-border { border-color: $color1; }
.color2-border { border-color: $color2; }
And so on.
I am looking for a way to write a loop so that when I use the variable to generate the class, it has the name of the variable rather than its value:
@each $color in $colour1, $colour2, $colour3, $colour4 {
.#{$color}-bg { background-color: $color; }
.#{$color}-border { border-color: $color; }
}
You can’t access the name of the variable directly, you’d have to store it as an additional value.
Sass 3.2 and older (list of lists)
Sass doesn’t have mappings yet, so the next best thing is a list of lists.
Sass 3.3 and newer (mappings)
Starting with 3.3, you have access to mappings. It’s functionally the same as the list of lists, but syntactically more concise.
Alternately
Or if your color names are really “color1”, “color2”, etc., you can also just construct the name on the fly rather than specifying them explicitly: