Last active
December 22, 2019 19:22
-
-
Save Merovex/e8aab31db09508d6f401923bd00010f0 to your computer and use it in GitHub Desktop.
Ensures color contrast for Accessibility, with decent granularity.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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