Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,242 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.