Skip to content

Instantly share code, notes, and snippets.

@mpalpha
Created January 24, 2020 14:43
Show Gist options
  • Save mpalpha/c0890df036d275be8df2bb4763622d2c to your computer and use it in GitHub Desktop.
Save mpalpha/c0890df036d275be8df2bb4763622d2c to your computer and use it in GitHub Desktop.
SASS: Adaptive Text Color Function
/*
* Adaptive Text Color Function
*
* Example:
* .text-contrast {
* color: adaptive-text-color(#fff);
* }
*
*/
// Calculates the square root of a number
@function sqrt($r) {
$x0: 1;
$x1: $x0;
@for $i from 1 through 10 {
$x1: $x0 - ($x0 * $x0 - abs($r)) / (2 * $x0);
$x0: $x1;
}
@return $x1;
}
// Calculates the brightness of a color
@function color-brightness($color) {
$red-component: red($color);
$green-component: green($color);
$blue-component: blue($color);
$red-magic-number: 241;
$green-magic-number: 691;
$blue-magic-number: 68;
$brightness-divisor: $red-magic-number + $green-magic-number + $blue-magic-number;
// Calculate a brightness value in 3d color space between 0 and 255
$number: sqrt((($red-component * $red-component * $red-magic-number) + ($green-component * $green-component * $green-magic-number) + ($blue-component * $blue-component * $blue-magic-number)) / $brightness-divisor);
// Convert to percentage and return
@return 100% * $number / 255;
}
// Apply the correct WCAG 2.1 text color with high enough contrast
@function adaptive-text-color($background: null, $threshhold: 65%, $light: #fff, $dark: #000) {
@if $background {
@return if(color-brightness($background) < $threshhold, $light, $dark);
} @else {
@error "ERROR: function `adaptive-text-color` requires a hex color value!";
@return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment