Willi
Willi

Reputation: 126

Referencing a sass/scss variable on the fly

I am trying to get a mixin done to achieve the following.

Im having a list of social buttons. They each share the same styles except the background-color and :hover states.

My current SASS approach. (will return invalid CSS error)

@mixin btn-social($network) {
    .#{$network} {
        background: $#{$network}; // trying to reference a global variable

            &:hover, &:focus {
                background: darken($#{$network}, $darken-modifier); 
            }
    }
}

To render like this:

.facebook {
    background: blue; // stored in $facebook
}
.facebook:hover, .facebook:focus {
    background: darkblue; //darkend value above
}

I'm somehow lacking the right terms for a proper google search. I'd appreciate a push in the right direction.

Thanks for the help.

Upvotes: 2

Views: 426

Answers (2)

Sam Willis
Sam Willis

Reputation: 4211

You can use a sass map to store the color variables and then find the right color using the name you pass into your mixin like so jsfiddle:

$colors: (
  facebook: blue,
  twitter: red
);
$darken-modifier: 100%;



@mixin btn-social($network) {
  .#{$network} {
    background: map-get($colors, $network);
    &:hover, &:focus {
      background: darken(map-get($colors, $network), $darken-modifier); 
    }
  }
}

@include btn-social(facebook);
@include btn-social(twitter);
<a class="facebook">
  facebook
</a>

<a class="twitter">
  twitter
</a>

Edit: updated to include @TomOakley's suggestion below.

Upvotes: 3

Julio Feferman
Julio Feferman

Reputation: 2676

Please try the following:

@mixin btn-social($network, $color, $darkColor) {
    #{$network}  {
        background: $color; 

            &:hover, &:focus {
                background: $darkColor;
            }
    }
}

.foo {
  @include btn-social('.facebook', blue, darkblue)
}

This compiles to:

.foo .facebook {
  background: blue;
}
.foo .facebook:hover, .foo .facebook:focus {
  background: darkblue;
}

Check out this reference for SASS interpolation.

Upvotes: 0

Related Questions