Use array value as variable [duplicate]

2019-01-20 17:27发布

问题:

This question already has an answer here:

  • Creating or referencing variables dynamically in Sass 5 answers

Let's say I have these colors:

$everlastingGreeN: #232553;
$vividRed: #3435454;
// and many more
//and define those:
$colors: (everlastingGreeN, vividRed);

How do I iterate those values so I can use the color name as the class name then the value as the background color?

@each $colors in $colors{
    &.#{$colors} {
        background: {color value};
        &:hover {
            background: darken({color value}, 10%);
        }
    }
}

回答1:

What you're looking for is a list of lists.

$everlastingGreeN: #232553;
$vividRed: #343545;
// and many more
//and define those:
$colors: everlastingGreeN $everlastingGreeN, vividRed $vividRed;

@each $color in $colors {
    &.#{nth($color, 1)} {
        background: nth($color, 2);
        &:hover {
            background: darken(nth($color, 2), 10%);
        }
    }
}


标签: sass