1
votes

With Sass, is it possible to determine if a color is greyscale?

Something like:

is-greyscale(#ffffff); // returns true

I can see it's possible to convert a color to greyscale in Sass, but I'm not sure how, if at all, this could be utilised to determine whether or not a given color is greyscale.

2

2 Answers

1
votes

Turns out it's surpsiginle easy, I figured it out immediately after posting this question:

@function is-grayscale($color) {
  @return if(grayscale($color) == $color, true, false);
}

@debug is-grayscale(white); // returns true
@debug is-grayscale(blue); // returns false
1
votes

The logic above is correct if the color is 100% grayscale, however there are plenty of colors that are "almost" grayscale, e.g. #DEDED9

The function below measures the saturation level of a color, and if the results are less than 8%, it considers the color to be grayscale.

Example:

@debug color.saturation(#DEDED9); // returns => 7.0422535211%
@debug color.saturation(#E2E2D5); // returns => 18.3098591549%

Functions:

@function is-color-grayscale($color){
    $saturation: color.saturation($color);

    @if ($saturation < 8%) {
        @return true;
    } @else{
        @return false;
    }
}

Results:

@debug is-color-grayscale(#DEDED9); // returns => true
@debug is-color-grayscale(#E2E2D5); // returns => false