Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS Sass Basics (retired) Advanced Sass Concepts Advanced Mixin Arguments

another sass code challenge: Design a mixin (called "rainbow") that can take any number of colors

this one lost me

Challenge Task 5 of 6

Design a mixin (called "rainbow") that can take any number of colors via the argument $colors.... Within the mixin, use the loop @each $color in $colors to create a class named after each color, and set its background to the corresponding color.

1 Answer

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Marty;

This one can be a bit of a challenge. Let's have a look...


Task 5

Design a mixin (called "rainbow") that can take any number of colors via the argument $colors.... Within the mixin, use the loop @each $color in $colors to create a class named after each color, and set its background to the corresponding color.


Not seeing code that you have tried, I'll take this step by step.

step1.css
@mixin rainbow($colors...) {}

When you use ... in the signature, Sass knows that it is an arglist for $colors and allows you to input a list of colors.

step2.css
@mixin rainbow($colors...) {
    @each $color in $colors {
        // Do stuff
    }
}

Setting up the @each loop to go through each of the colors in our arglist and assign it to the $color variable.

step3.css
@mixin rainbow($colors...) {
    @each $color in $colors {
        .#{$color} {
           // set our styling
        }
    }
}

Target and create our classes with color names.

step4.css
@mixin rainbow($colors...) {
  @each $color in $colors {
    .#{$color} {
          background: $color; } 
  }
}

Now if we do an @include rainbow(blue, green, red, brown) Sass will generate for us:

.blue {
  background: blue;
}

.green {
  background: green;
}

.red {
  background: red;
}

.brown {
  background: brown;
}

Hope it helps. Post back if you are still stuck.

Happy coding,
Ken

Thank you Ken. I was close but your answer helped me get it exactly right