Calling variables dynamically in SCSS [duplicate]

2019-02-23 08:51发布

问题:

This question already has an answer here:

  • Creating or referencing variables dynamically in Sass 5 answers

I have a series of color variables for my site that are numbered off:

$red-1: #821B0D;
$red-2: #B13631;
$red-3: #D75B5B;
$red-4: #F18788;
$red-5: #FDB9B0;

I'd like to set up a mixin that calls them dynamically, like this:

@mixin link($color-name) {
    color: $#{$color-name}-2;
    &:hover {
        color: white;
        background-color: $#{$color-name}-4;
    }
}

However, I can't figure how to call variables in a manner like this. (The above syntax doesn't work.)

(To head off the obvious suggestion: I'm not using SASS' color functions because my colors aren't set by linear saturation or lightness variations. I can't generate them programmatically in SASS. The lightness shift in reds between steps is not the same as the one between blues, which isn't the same as the one for greens, etc.)

回答1:

First off, the reason your suggested syntax doesn't work is because when interpolations are included in property values, the text around it (such as the '$' symbol) is interpreted as plain CSS. This is noted in the SASS reference on interpolations.

I'd suggest using SASS lists instead. Something like this would give you the functionality you're after:

@mixin link($color) {
    color: nth($color, 2);
    &:hover {
        color: white;
        background-color: nth($color, 4);
    }
}

$red: (#821B0D, #B13631, #D75B5B, #F18788, #FDB9B0);

.test {
    @include link($red);
}

(Note that the index values passed to the nth() function are one-based, not zero-based.)



标签: sass