3

I want to use a SCSS loop as below:

@each $var in dark, purple, green, cyan, silver, white {

  .text-#{$var} {
    color: nth($color-, $var);
  }
  .btn-#{$var} {
    background-color: nth($color-, $var);
  }
}

in order to use the following variables:

$color-dark: #0D0E1E;
$color-purple: #333366;
$color-green: #33cc99;
$color-cyan: #00cccc;
$color-silver: #ccc;
$color-white: #fff;

but it is not working. $color-#{$var} was not working as well. Can I do this?

masfmqowkf
  • 121
  • 12
  • 1
    Possible duplicate of [Creating or referencing variables dynamically in Sass](https://stackoverflow.com/questions/8533432/creating-or-referencing-variables-dynamically-in-sass) – fubar Oct 11 '17 at 23:13

1 Answers1

2

nth gets an item in a list. The first argument is the list, the 2nd is an index in the list. Also SASS thinks anything with a $ is a variable, so $color- is a variable. You haven't defined $color- as a variable, and that's not your intended use.

DOCS.

But you can get your desired result with a map...

DEMO

$color-dark: #0D0E1E;
$color-purple: #333366;
$color-green: #33cc99;
$color-cyan: #00cccc;
$color-silver: #ccc;
$color-white: #fff;

$colors: (
  dark: $color-dark,
  purple: $color-purple,
  green: $color-green,
  cyan: $color-cyan,
  silver: $color-silver,
  white: $color-white
);

@each $name, $val in $colors {
  .text-#{$name} {
    color: $val;
  }

  .btn-#{$name} {
    background-color: $val;
  }
}
Ari
  • 1,595
  • 12
  • 20