1

I'm trying to rewrite some SCSS to reduce duplicate code written below...

.bg-primary {
   background: $primary;
}
.bg-secondary {
   background: $secondary;
}
.bg-tertiary {
   background: $tertiary;
}

...to something like this:

$colors: primary secondary tertiary;

@each $color in $colors {
   .bg-#{$color}{
      background: $color;
   }
}

The problem however is that background: $color will output background: primary; instead of background: $primary; which on his turn should be processed as background: #000;. Any thoughts on how I could make this work? Thanks!

MvdLanden
  • 13
  • 3

1 Answers1

0

One way would be to define a color map with key-value pairs. The key then can be used as part of the class name:

$colors: (primary: #000, secondary: #f00, tertiary: #00f);

@each $colorkey, $value in $colors {
   .bg-#{$colorkey}{
      background: $value;
   }
}

To use the colors elsewhere you would then have to use

.example {
  color: map-get($colors, tertiary);
}

In some scenarios the color values are already defined, e.g. by an underlying framework. It is possible to use previously defined colors in your map, but of course this will bring some redundancy that you can't avoid if you want to use individual variables in a loop (duplicated variable names):

$primary: #000;
$secondary: #f00;
$tertiary: #00f;

$colors: (primary: $primary, secondary: $secondary, tertiary: $tertiary);
/* loop see above... */

On the other hand this makes it easier to access the colors elsewhere.

Marvin
  • 9,164
  • 3
  • 26
  • 44
  • Thank you for looking into this. Your solution works, however does not feel very natural to me. Do you know of a way to simply add a $ sign to the $color output? Something like `background: $#{$color}`. – MvdLanden Mar 07 '17 at 13:27
  • I totally understand you and it would be great to have a way of referencing dynamically created variables. I had a look in the specification and did a quick research before I posted the answer but I couldn't find anything useful for this scenario. All I know is that this question came up multiple times [already several years ago](http://stackoverflow.com/questions/6010013/is-it-possible-to-reference-a-variable-with-an-interpolated-string), it was once solved by using lists and then by using the later introduced maps. – Marvin Mar 07 '17 at 16:35
  • I'm gonna mark this as the answer since there doesn't seem to be another way and this solution makes it slightly cleaner. Thanks [Marvin](http://stackoverflow.com/users/3162554/marvin) – MvdLanden Mar 16 '17 at 13:46