Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
624 views
in Technique[技术] by (71.8m points)

css - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...