Search code examples
csscompass-sasssass

Scss mixin function variable scope


Not shure if this is a scope issue, well consider the following:

$custom : #f20;

@mixin colorbyclass($class) {
  .#{$class} {
    background: $class;
  }
}

//scss
@include colorbyclass(custom);

//compiles
.custom { color:custom; }

My issue being that i want $class to be a reference to my variable inside the function.
http://jsfiddle.net/yTkqp/

I'm up for grabs for suggestions to alternative solutions.


Solution

  • Variable variables don't exist in Sass. For the mixin you've presented, you can either pass it a single list containing 2 values or pass 2 values.

    Option #1:

    $custom : #f20;
    @mixin colorbyclass($value) {
      &.#{nth($value, 1)} {
        background: nth($value, 2);
      }
    }
    .container {
      div {
        width:20px;
        height:20px;
        @include colorbyclass(custom $custom);
      }
    }
    

    Option #2:

    $custom : #f20;
    @mixin colorbyclass($class, $color) {
      &.#{$class} {
        background: $color;
      }
    }
    .container {
      div {
        width:20px;
        height:20px;
        @include colorbyclass(custom, $custom);
      }
    }
    

    Though, they look just as verbose as not using a mixin at all:

    .container {
      div {
        width:20px;
        height:20px;
        &.custom {
            background: $custom; // could easily be replaced with a mixin that sets a bg color + other stuff
        }
      }
    }