14

hi i have many variables with colors. so want do something like this:

$culture: #00CC66;
$party:#CC9900;

 @each $i in culture, party {
.bl_#{$i}{
   border-left-color: #{$#{$i}};
}
}

for print:

bl_culture{border-left-color:#00cc66}
bl_party{border-left-color:#cc9900}

How can ido it?

thanks

Luca Romagnoli
  • 12,145
  • 30
  • 95
  • 157
  • 2
    possible duplicate of [Sass make dynamic variable by connecting string and $var](http://stackoverflow.com/questions/8533432/sass-make-dynamic-variable-by-connecting-string-and-var) – cimmanon Aug 30 '15 at 12:56

2 Answers2

21

SASS 3.3 UPDATE
With some new functionality from sass 3.3 you can choose your variable names and do away with the annoying nth()

@each $name, $color in(
    'red'   $red,
    'green' $green,
) {
    .color-#{$name} {
        background-color: $color;
    }
}

ORIGINAL
It's a bit of a pain but you can get by with a list and then for looping through that.
For example:

$colorList:
    "red"    $red,
    "green"  $green
;

@each $i in $colorList{
    .color-#{nth($i,1)}{
         background-color:nth($i,2);
    }
}

Having pre defined these color vars elsewhere you get:

.color-red{
   background-color:#FF0000
}

.color-green{
   background-color:#00FF00
}
Allan Hortle
  • 2,435
  • 2
  • 20
  • 22
6

As sad as it is, you can't. SASS will only parse your file once, so even if you do something like this :

$culture: #00CC66;
$party:#CC9900;

@each $i in culture, party {
  .bl_#{$i}{
     border-left-color: #{'$' + $i};
  }
}

You will end up with the following CSS :

.bl_culture {
  border-left-color: $culture; }

.bl_party {
  border-left-color: $party; }

Your best bet is probably to change your code for something like :

.bl {
  [...]

  &.culture {
    border-left-color: #00CC66
  }
  &.party {
    border-left-color: #CC9900
  }
}

And then use something like class="bl culture" instead of class="bl_culture".

Leo
  • 5,069
  • 2
  • 20
  • 27
  • do we have the same support in scss file extension – Jazmin Oct 19 '14 at 07:48
  • 1
    @Jazmin Yes. You should probably take a look at Allan Hortle's answer below, it should actually be marked as the right answer. – Leo Oct 20 '14 at 13:16