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:
You can't access the name of the variable directly, you'd have to store it as an additional value.
Sass doesn't have mappings yet, so the next best thing is a list of lists.
$color1: ('color1', blue);
$color2: ('color2', red);
$color3: ('color3', white);
$color4: ('color4', black);
@each $color in $color1, $color2, $color3, $color4 {
$name: nth($color, 1);
$value: nth($color, 2);
.#{$name}-bg { background-color: $value; }
.#{$name}-border { border-color: $value; }
}
Starting with 3.3, you have access to mappings. It's functionally the same as the list of lists, but syntactically more concise.
$colors:
( 'color1': blue
, 'color2': red
, 'color3': white
, 'color4': black
);
@each $name, $value in $colors {
.#{$name}-bg { background-color: $value; }
.#{$name}-border { border-color: $value; }
}
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:
$color1: blue;
$color2: red;
$color3: white;
$color4: black;
$num: 0;
@each $color in ($color1, $color2, $color3, $color4) {
$num: $num + 1;
.color#{$num}-bg { background-color: $color; }
.color#{$num}-border { border-color: $color; }
}
According to the sass-reference your code should look like this, but i haven´t tried it myself.
@each $color in $color1, $color2, $color3, $color4 {
.#{$color}-bg { background-color: $color;}
.#{$color}-border { border-color: $color;}
}
http://sass-lang.com/docs/yardoc/file.SASS_REFERENCE.html#control_directives
Ya, this is quite some time from the op, but thought, I'd add it anyway :)
This is what you are looking for with the least amount of repetition. You can just add new colors to your $eric-holmes-colors array and recompile.
$eric-holmes-colors: "blue", "red", "white", "black";
@each $color in $eric-holmes-colors {
.#{$color}-bg {
background-color: #{$color};
}
.#{$color}-border {
border-color: #{$color};
}
}
This is more of a comment on the previous answers. It's possible to combine both answers, which results in pretty elegant code (in my not-so-humble opinion).
I use Dutch color names, I do so on purpose as to make clear we're not dealing with HTML color names.
$rood : #e3004a;
$blauw : #009ee0;
@each $color in ('rood', $rood), ('blauw', $blauw) {
$name: nth($color, 1);
$value: nth($color, 2);
.#{$name} {
a{
background-color: $value;
}
}
}
CSS
.rood a { background-color: #e3004a; }
.blauw a { background-color: #009ee0; }