Search code examples
csssasscompass-sass

Sass @each with multiple variables


I'm just getting started with Sass and Compass, and I'm loving it. Something I'd like to do is take advantage of the @each function to simplify repetitive tasks. However, I've only seen examples of @each inserting one variable, and I'd like to be able to use multiple variables.

The standard way (from the Sass Reference):

@each $animal in puma, sea-slug, egret, salamander {
  .#{$animal}-icon {
    background-image: url('/images/#{$animal}.png');
  }
}

Which is great, but I'd like to be able to do something like:

@each {$animal $color} in {puma black}, {sea-slug green}, {egret brown}, {salamander red} {
  .#{$animal}-icon {
    background-color: #{$color};
  }
}

Is this possible?


Solution

  • I'm in the same boat (beginner to Sass/Compass) and had to do something similar. Here's what I came up with, using nested lists:

    $flash_types: (success #d4ffd4) (error #ffd5d1);
    
    @each $flash_def in $flash_types {
        $type: nth($flash_def, 1);
        $colour: nth($flash_def, 2);
    
        &.#{$type} {
            background-color: $colour;
            background-image: url(../images/#{$type}.png);
        }
    }
    

    It's not the most elegant solution but it should work if you can't find anything else. Hope it helps! I'd appreciate a better method too :)