Sass Loop through array and current variable
I am trying to loop through my list of colors to change the background color. But the following fails.
$speech-bubble-default: $colors-chalk;
$speech-bubble-blush: $colors-blush;
$speech-bubble-brick: $colors-brick;
$speech-bubble-pink: $colors-pink;
$speech-bubble-slate: $colors-slate;
$colors-list: blush brick default pink slate;
@each $current-color in $colors-list {
&.speech-bubble--#{$current-color} {
background-color: $speech-bubble--#{$current-color};
&::after {
border-bottom-color: $speech-bubble--#{$current-color};
}
}
}
'Error: variable Undefined: "$ speech-bubble -"
Is there a way to make this work in a loop?
I think you need to make it easier. I would create a list to manage colors. This way you create variables correctly and avoid code repetition.
$colors-list:(
default: 'chalk',
blush: 'blush',
brick: 'brick',
pink: 'pink',
slate: 'slate'
);
If you want a more descriptive and semantic way to separate a color name to its functionality, you can nest a variable color list like this:
$chalk: 'chalk';
$blush: 'blush';
$brick: 'brick';
$pink: 'pink';
$slate: 'slate';
$colors-list:(
default: $chalk,
blush: $blush,
brick: $brick,
pink: $pink,
slate: $slate
);
The problem in your code is that you are trying to refer to variables by interpolation #{}
and the interpolation of variable names is not supported by SASS, Variables are called on their entire name. You are also repeating color lists.
Why not:
@each $key,$val in $colors-list{
.speech-bubble--#{$key} {
background-color: #{$val};
}
}
source to share