Videl Videl - 1 month ago 16
Sass (Sass) Question

Sass - a way to invert Lighten/Darken function by variable?

I'm trying to think of a simple way to invert the darken/lighten color function using a variable. Something like so...

$invert_switch: off;


And...

@if $invert_switch == "on" {
darken == lighten
lighten == darken
} @else {
darken == darken
lighten == lighten
}


I know that's not proper code, I'm just trying to explain it very simply.

If this was used...

background: darken($bg, 10%);
color: lighten($txt, 50%);


How could I flip that, so it would be...

background: lighten($bg, 10%);
color: darken($txt, 50%);


Or maybe there is an easier way?

Answer

I try to change the name of the functions darken and lighten but I can't. The problem I have found is that SASS haven't something like @break or @continue to exit for the function and do nothing, my idea was the following code but when the custom fuction coincides with the SASS function goes to a infinite loop:

$invert_switch: on;

@function darken($color, $amount){
  @if $invert_switch == on {
    @return lighten($color, $amount);
  }
  @else {
    @return darken($color, $amount);
  }
}

@function lighten($color, $amount){
  @if $invert_switch == on {
    @return darken($color, $amount);
  }
  @else {
    @return lighten($color, $amount);
  }
}


h1{
  color: darken(red, 10%);
}

p{
  color: lighten(red, 10%);
}

I change the name of the functions adding a underscore to work:

$invert_switch: on;

@function _darken($color, $amount){
  @if $invert_switch == on {
    @return lighten($color, $amount);
  }
  @else {
    @return darken($color, $amount);
  }
}

@function _lighten($color, $amount){
  @if $invert_switch == on {
    @return darken($color, $amount);
  }
  @else {
    @return lighten($color, $amount);
  }
}


h1{
  color: _darken(red, 10%);
}

p{
  color: _lighten(red, 10%);
}

Maybe someone can improve this code using the proper names of functions

Comments