Dynamic variable switching in SCSS

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

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

I would like to configure mixin, which calls them dynamically, for example:

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

However, I cannot figure out how to call variables in this way. (The syntax above does not work.)

(To avoid the obvious assumption: I do not use SASS color functions because my colors are not set by linear changes in saturation or brightness. I cannot programmatically generate them in SASS. The steps are not the same as between a blues that does not match what is indicated for greens, etc.)

+4
source share
1 answer

First, the reason your suggested syntax does not work is because when interpolations are included in property values, the text around it (for example, the "$" character) is interpreted as plain CSS. This is noted in the SASS interpolation link.

I would suggest using SASS lists . Something like this will give you the functionality you use:

 @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 nth () are based on one, not zero.)

+5
source

Source: https://habr.com/ru/post/1413421/


All Articles