mrbut
mrbut

Reputation: 665

Updating variables created by lighten/darken functions by modifying the original base color afterwards

I'm currently trying to create a mix-in that will let me build buttons with hover values using the darken and lighten color functions in sass. My code for some reason is spitting out white and black for the background color instead of the hex value of a returned color. Here it is on code pen: http://codepen.io/malikabee/pen/vEQZOv

$btn_color: #fff;
$btn_alpha: 1;
$btn_color_amount: 100%;

$color_funcs: (
  'darken': darken($btn_color, $btn_color_amount), 
  'lighten': lighten($btn_color, $btn_color_amount),
  'transparentize': transparentize($btn_color, $btn_alpha)
);

@mixin _btn_color($base_color, $amount, $hover){
  background: $base_color;
  a:hover,
  a:focus{
    @each $func_name, $color_func in $color_funcs{
      @if($func_name == $hover){
         $btn_color: $base_color;
         $btn_color_amount: $amount;
         background-color: $color_func;
      }
    }
  }
}

 .btn{
   display: inline-block;
   vertical-align: bottom;
   text-align: center;
   border-radius: 10px;
   text-decoration: none;
 }

.btn_blue{
  @include _btn_color(#3c3c3c, 10%, 'darken');
}

Upvotes: 0

Views: 152

Answers (1)

cimmanon
cimmanon

Reputation: 68319

Once you get past this block of code, the expressions don't exist anymore, only the value they evaluated to does:

$color_funcs: (
  'darken': darken($btn_color, $btn_color_amount), 
  'lighten': lighten($btn_color, $btn_color_amount),
  'transparentize': transparentize($btn_color, $btn_alpha)
);

Changing $btn_color after this point does nothing. Sass cannot to go back in time and re-run those expressions because they've already been evaluated using the original color (black).

What you can do instead is use the call function.

@mixin _btn_color($base_color, $amount, $func){
  background: $base_color;
  a:hover,
  a:focus{
    background-color: call($func, $base_color, $amount);
  }
}

.btn_blue{
  @include _btn_color(blue, 10%, 'darken');
  color: white;
}

Upvotes: 1

Related Questions