Skip to content

Instantly share code, notes, and snippets.

@sgomes
Last active September 27, 2022 12:36
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sgomes/9c03a58976b90e00f4172a510b9807fa to your computer and use it in GitHub Desktop.
Save sgomes/9c03a58976b90e00f4172a510b9807fa to your computer and use it in GitHub Desktop.
[Using Sass to automatically pick text colors] #4 - step 2
/**
* Calculate the luminance for a color.
* See https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
*/
@function luminance($color) {
$red: nth($linear-channel-values, red($color) + 1);
$green: nth($linear-channel-values, green($color) + 1);
$blue: nth($linear-channel-values, blue($color) + 1);
@return .2126 * $red + .7152 * $green + .0722 * $blue;
}
/**
* Calculate the contrast ratio between two colors.
* See https://www.w3.org/TR/WCAG20-TECHS/G17.html#G17-tests
*/
@function contrast($back, $front) {
$backLum: luminance($back) + .05;
$foreLum: luminance($front) + .05;
@return max($backLum, $foreLum) / min($backLum, $foreLum);
}
/**
* Determine whether to use dark or light text on top of given color.
* Returns black for dark text and white for light text.
*/
@function choose-contrast-color($color) {
$lightContrast: contrast($color, white);
$darkContrast: contrast($color, black);
@if ($lightContrast > $darkContrast) {
@return white;
}
@else {
@return black;
}
}
@WynieCronje
Copy link

Where do I get the $linear-channel-values ?

@artlung
Copy link

artlung commented May 11, 2021

@sgomes
Copy link
Author

sgomes commented May 12, 2021

Sass now supports pow, which removes the need for a lookup table in the first place, making the article I wrote partially obsolete 🙂
This is a good thing!

If you're looking to implement something like choose-contrast-color nowadays, I would suggest looking at the current implementation of Material Components Web, specifically the contrast-tone function: https://github.com/material-components/material-components-web/blob/master/packages/mdc-theme/_theme-color.scss

The above link is valid as of May 2021, but if you're reading this in the distant future, I'm sure you'll be able to find the relevant code somewhere in the Material Components Web repo, or whatever succeeds it.

@artlung
Copy link

artlung commented May 12, 2021

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment