Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sass @each with multiple variables

Tags:

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?

like image 552
steve Avatar asked Jul 04 '11 14:07

steve


People also ask

What is @each in Sass?

The @each rule makes it easy to emit styles or evaluate code for each element of a list or each pair in a map. It's great for repetitive styles that only have a few variations between them. It's usually written @each <variable> in <expression> { ... } , where the expression returns a list.

How many syntaxes that Sass support?

Sass consists of two syntaxes.

What is variable interpolation in Sass?

Interpolation allows us to interpolate sass expressions into a simple SASS or CSS code. Means, you can define ( some part or the whole ) selector name, property name, CSS at-rules, quoted or unquoted strings etc, as a variable. Interpolation is a new principle and it is widely used in SASS.

Which datatype allows you to represent multiple values using comma or space seperator?

Lists. Lists specify multiple values which are separated using spaces or commas. Even single value are considered as a list.


1 Answers

Just came across this, have the answer for you. In Sass, you can actually have a multidimensional list, so instead of constructing individual variables, you'd create one variable to hold them all, then loop over them:

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

You can have multidimensional lists just like you would have single dimensional lists as long as each nested dimension is separated in a different manner (in our case, commas and spaces).

UPDATE Oct 24, 2013

In Sass 3.3, there is a new data type called maps which are a hashed set of items. With this, we can rewrite my previous answer in the following way to much more closely resemble the desired result:

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

You can see this in action over at SassMeister

like image 194
Snugug Avatar answered Jun 13 '23 02:06

Snugug