Skip to content

Instantly share code, notes, and snippets.

@Merovex
Last active December 22, 2019 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Merovex/e8aab31db09508d6f401923bd00010f0 to your computer and use it in GitHub Desktop.
Save Merovex/e8aab31db09508d6f401923bd00010f0 to your computer and use it in GitHub Desktop.
Ensures color contrast for Accessibility, with decent granularity.
@function pow($base, $exponents) {
$raised: 1;
@for $i from 1 through $exponents {
$raised: $raised * $base;
}
@return $raised;
}
@function luma($color){
// Thanks voxpelli for a very concise implementation of luminance measure in sass
// Adapted from: https://gist.github.com/voxpelli/6304812
$rgba: red($color), green($color), blue($color);
$rgba2: ();
@for $i from 1 through 3 {
$rgb: nth($rgba, $i);
$rgb: $rgb / 255;
$rgb: if($rgb < .03928, $rgb / 12.92, pow(($rgb + .055) / 1.055, 2.4));
$rgba2: append($rgba2, $rgb);
}
@return (.2126 * nth($rgba2, 1) + .7152 * nth($rgba2, 2) + 0.0722 * nth($rgba2, 3))*100;
}
@function contrast_ratio($color1, $color2) {
$luma1: luma($color1) + 5;
$luma2: luma($color2) + 5;
$ratio: $luma1 / $luma2;
@if $luma1 < $luma2 {
$ratio: 1 / $ratio;
}
@return $ratio;
}
@function contrast($color, $bgcolor: $color, $threshold:5.0) {
// $threshold: 4.5; // 4.5 = WCAG AA,7= WCAG AAA
// $threshold: 5.0;
$list: 0,7,14,21,28,35,42,49,56,63,70,77,84,91;
@each $percent in $list {
$lighter: lighten($color, $percent);
$darker: darken($color, $percent);
$darker-ratio: contrast_ratio($bgcolor, $darker);
$lighter-ratio: contrast_ratio($bgcolor, $lighter);
// @debug $percent LR $lighter-ratio DR $darker-ratio TH $threshold light(lightness($color));
@if($darker-ratio > $lighter-ratio){
@if ($darker-ratio > $threshold){
@return $darker;
}
}
@if($lighter-ratio > $darker-ratio){
@if ($lighter-ratio > $threshold){
@return $lighter;
}
}
}
@return if(lightness($color) < 51, #000, #FFF) // Couldn't find an answer
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment