0

I'm trying to use an each loop in Sass but the css is compiling with the variable name instead of the content of the variable.

$green-1: #9ae200;
$green-2: #5ea600;
$color-list: green-1 green-2;

@each $single-color in $color-list {
    &.#{$single-color} {
        background-color: $single-color;
    }
}

The output I am looking for is:

.green-1 {
    background-color:#9ae200;
}
.green-2 {
    background-color:#5ea600;
}

But the css is compiling as:

.green-1 {
    background-color:green-1;
}
.green-2 {
    background-color:green-2;
}

So to try to get the dollar sign in there I tried this:

@each $single-color in $color-list {
    @function create-variable($variable){
        @return "$" + $variable;
    }

    &.#{$single-color} {
        background-color: create-variable($single-color);
    }
}

But that compiled as:

.green-1 {
    background-color:$green-1;
}
.green-2 {
    background-color:$green-2;
}

Sass is not reading the variables for some reason and is taking them literally. Anyone know how to make this work?

EthanNYC
  • 13
  • 2

1 Answers1

2

You cannot create dynamic variable in sass. Instead you can achieve your desired result using map

example:

$green-1: #9ae200;
$green-2: #5ea600;
$color-map: (
  green-1: $green-1, 
  green-2:  $green-2,
);

.body{
  @each $key,$value in $color-map {
      &.#{$key} {
          background-color: $value;
      }
  }
}
karthick
  • 11,550
  • 5
  • 52
  • 83