0

I tried to make the following code look fancier with an @each or a @for loop (without any usable result).

.btn[data-btn-color="black"] {
    @include colored-btn($black);
}
.btn[data-btn-color="blue"] {
    @include colored-btn($blue);
}
.btn[data-btn-color="red"] {
    @include colored-btn($red);
}
// ... and more colors ...

My current approach is to take value from the variable to use it as the value for the data-btn-color attribute and put that snippet into an @each loop.

Something like

@each $color in ($black, $blue) {
    @include colored-btn($color);
}

which compiles into:

.btn[data-btn-color="black"] {
  background-color: #000; // $black
}
.btn[data-btn-color="blue"] {
  background-color: #00f; // $blue
}

Is there any function, which allows me to do such a thing?

Jon Lamer
  • 408
  • 6
  • 12
  • possible duplicate of [Use array value as variable](http://stackoverflow.com/questions/14794220/use-array-value-as-variable) – cimmanon Dec 17 '13 at 21:41
  • 1
    See also: http://stackoverflow.com/questions/15757665/sass-color-variable-hex-output – cimmanon Dec 17 '13 at 21:42

1 Answers1

1

You were so close! You don't want the () around what you want to go through in @each. I think Sass would just see what you have as one list item with a two item list inside.

Here is what I think you're trying to do:

$red: #f00;
$blue: #00f;
$black: #000;

$colors:  red $red, blue $blue, black $black;

@mixin colored-button($background-color: #000){
  background-color: $background-color;
}

@each $color in $colors {
  $name: nth($color, 1);
  $hex: nth($color, 2);
  .btn[data-btn-color="#{$name}"]{
    @include colored-button($hex);
  }
}

Which would result in:

.btn[data-btn-color="red"] {
  background-color: red; }

.btn[data-btn-color="blue"] {
  background-color: blue; }

.btn[data-btn-color="black"] {
  background-color: black; }
Bill Criswell
  • 32,161
  • 7
  • 75
  • 66
  • i got that with the list item, but use "$blue: rgb( 34, 147, 194);" and not the predefined css colors, which makes it look like data-btn-color="#ffcd3d" – Jon Lamer Dec 17 '13 at 21:30
  • 1
    I've updated it. I was confused because Sass was changing the colors to their CSS names. – Bill Criswell Dec 17 '13 at 21:41