Skip to content

Instantly share code, notes, and snippets.

@mudcube
Created October 22, 2016 02:59
Show Gist options
  • Select an option

  • Save mudcube/5f4e46ce552600caeae554afa900ec73 to your computer and use it in GitHub Desktop.

Select an option

Save mudcube/5f4e46ce552600caeae554afa900ec73 to your computer and use it in GitHub Desktop.
Determine whether the difference between two colors meets the W3 standards for contrast.
@function isW3Contrast($rgb1, $rgb2) {
$rgb1: red($rgb1), green($rgb1), blue($rgb1);
$rgb2: red($rgb2), green($rgb2), blue($rgb2);
$brightness: W3Brightness($rgb1, $rgb2) <= 125;
$difference: W3Difference($rgb1, $rgb2) <= 500;
@if ($brightness and $difference) {
@return false;
} @else {
@return true;
}
}
@function W3Brightness($a, $b) { // color brightness >= 125.
$aa: ((nth($a, 1) * 299) + (nth($a, 2) * 587) + (nth($a, 3) * 114)) / 1000;
$bb: ((nth($b, 1) * 299) + (nth($b, 2) * 587) + (nth($b, 3) * 114)) / 1000;
@return abs($aa - $bb);
}
@function W3Difference($a, $b) { // color difference >= 500
$r: max(nth($a, 1), nth($b, 1)) - min(nth($a, 1), nth($b, 1));
$g: max(nth($a, 2), nth($b, 2)) - min(nth($a, 2), nth($b, 2));
$b: max(nth($a, 3), nth($b, 3)) - min(nth($a, 3), nth($b, 3));
@return $r + $g + $b;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment