Skip to content

Instantly share code, notes, and snippets.

@jhafner
Created October 25, 2016 16:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhafner/e280bd140a1481ced5ccb710d0be68ac to your computer and use it in GitHub Desktop.
Save jhafner/e280bd140a1481ced5ccb710d0be68ac to your computer and use it in GitHub Desktop.
Sass functions for accessible text contrast.
// Power utility to calculate exponents
@function pow($number, $exponent) {
$value: 1;
@if $exponent > 0 {
@for $i from 1 through $exponent {
$value: $value * $number;
}
} @else if $exponent < 0 {
@for $i from 1 through -$exponent {
$value: $value / $number;
}
}
@return $value;
}
// Luminance Calulations
@function luma($color){
// 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;
}
// Contrast Ratios
@function contrast_ratio($color1, $color2) {
$luma1: luma($color1) + 5;
$luma2: luma($color2) + 5;
$ratio: $luma1 / $luma2;
@if $luma1 < $luma2 {
$ratio: 1 / $ratio;
}
@return $ratio;
}
// Calculate Proper Text Contrast
//
// Adapted from: https://madebymike.com.au/writing/accessible-contrast-with-less-and-sass/
//
// Usage:
//
// .my-element
// background: $backgroud-color
// color: text-contrast($backgroud-color)
//
// Optional, pass in text color to control text color
//
// .my-element
// background: $backgroud-color
// color: text-contrast($backgroud-color, DarkSalmon)
@function text-contrast($color, $bgcolor: $color) {
$threshold: 4.5; // 4.5 = WCAG AA,7= WCAG AAA
$list: 20 30 40 50 60 70 80 90 100;
@each $percent in $list {
$lighter: lighten($bgcolor, $percent);
$darker: darken($bgcolor, $percent);
$darker-ratio: contrast_ratio($color, $darker);
$lighter-ratio: contrast_ratio($color, $lighter);
@if($lighter-ratio > $darker-ratio){
@if ($lighter-ratio > $threshold){
@return $lighter;
}
}
@if($darker-ratio > $lighter-ratio){
@if ($darker-ratio > $threshold){
@return $darker;
}
}
}
@return if(lightness($color) < 51, #FFF, #000)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment