masfmqowkf
masfmqowkf

Reputation: 121

Using SCSS variable inside a variable

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?

Upvotes: 3

Views: 2036

Answers (1)

Ari
Ari

Reputation: 1703

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;
  }
}

Upvotes: 2

Related Questions