0

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);
}
Mo.
  • 26,306
  • 36
  • 159
  • 225
  • You can use variadic arguments in sass. Just do the variable name and three dots. Ex. `@function colorcontrast($color, $args...) { ... }` – watzon Nov 21 '17 at 22:49
  • Yah, but unfortunately I am totally stuck to build comparing argument with multiple colors – Mo. Nov 21 '17 at 22:52

1 Answers1

1

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.

3rdthemagical
  • 5,271
  • 18
  • 36
  • thanks you very much for your response. Could you please let me know why we are using `$base-color-brightness: brightness($base-color);` twice ? – Mo. Nov 22 '17 at 07:34
  • Can we implement some ideas to your answer from this snippet https://www.sassmeister.com/gist/fbf10a893625e8bc32d81a324d09a0a5 ? – Mo. Nov 22 '17 at 09:07
  • Muhammed Athimannil, `$base-color-brightness` calculates only one time at line 12 (see sassmeister demo). – 3rdthemagical Nov 22 '17 at 11:28