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

Stephen O'Connor
Stephen O'Connor
22,291 Points

Mixin Question...

I need help with mixins and scope/arguments.

$color: red;

@mixin colors($color: blue) {
  background-color: $color;
  @content;
  border-color: $color;
}

.colors {
  @include colors {
    color: $color;
  }
}

Produces

.colors {
  background-color: blue;
  color: red;
  border-color: blue;
}

And I don't understand why color is red and not blue. Any pointers?

Thanks!

2 Answers

Joel Bardsley
Joel Bardsley
31,246 Points

From the Sass documentation:

The block of content passed to a mixin are evaluated in the scope where the block is defined, not in the scope of the mixin. This means that variables local to the mixin cannot be used within the passed style block and variables will resolve to the global value:

If you wanted to get around it, you could set a global variable within your mixin that can be used within the @include as follows:

$color: red;

@mixin colors($color: blue) {
  $thisColor: $color !global;
  background-color: $color;
  @content;
  border-color: $color;
}

.colors {
  @include colors {
    color: $thisColor;
  }
  border-color: $color;
}

compiles to:

.colors {
  background-color: blue;
  color: blue;
  border-color: blue;
  border-color: red;
}

Hope that helps.