Sass @each with multiple variables

前端 未结 5 1695
生来不讨喜
生来不讨喜 2020-11-30 01:58

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 ta

5条回答
  •  旧时难觅i
    2020-11-30 02:29

    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

提交回复
热议问题