How to make sass color compare function with multiple parameters?

878 Views Asked by At

The current colorcontrast function comparing with three colors only. Looking for best solution to build with multiple parameters like @function colorcontrast($color, $rest...) { for color: colorcontrast(yellow, blue, orange, tomato, deekskyblue); but not sure how to compare with all the listed colors.

@function brightness($color) {
  @return ((red($color) * .299) + (green($color) * .587) + (blue($color) * .114)) / 255 * 100%;
}
@function colorcontrast($color, $dark, $light) {
    $color-brightness: brightness($color);
    $light-text-brightness: brightness($light);
    $dark-text-brightness: brightness($dark);
    @return if(abs($color-brightness - $light-text-brightness) > abs($color-brightness - $dark-text-brightness), $light, $dark);
}

.my-div{
  padding: 1rem;
  background-color: yellow;
  color: colorcontrast(yellow, #000, #fff);
}
1

There are 1 best solutions below

3
On

All you need is to calculate contrasts for all colors of the list in a loop. And choose a color with the best contrast to the base color.

@function brightness($color) {
  @return ((red($color) * .299) + (green($color) * .587) + (blue($color) * .114)) / 255 * 100%;
}

@function color-contrast($base-color, $colors...) { 
    // $colors... - means variadic arguments as Chris W says

    // Suppose that the best color is the first in the colors list
    $best-color: nth($colors, 1);
    $best-color-brightness: brightness($best-color);

    $base-color-brightness: brightness($base-color);

    @each $color in $colors {
      $color-brightness: brightness($color);

      // If the new color ($color) is more contrast than the previous one, 
      // remember it as the $best-color
      @if(abs($base-color-brightness - $color-brightness) > abs($base-color-brightness - $best-color-brightness)) {
        $best-color: $color;
        $best-color-brightness: $color-brightness;
      }
    }

    @return $best-color;
}

SassMeister demo.
Documentation for @each directive.