Last active
May 13, 2021 22:49
-
-
Save vimtaai/6d9556e7b7ab5d8f744afe0b7432e787 to your computer and use it in GitHub Desktop.
Functions to calculate luminance of colors and contrast ratio of colors in SASS
This file contains 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
// Calulates power with integer exponent | |
@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; | |
} | |
// Calculates nth root with iteration | |
@function nth-root($value, $n) { | |
$precision: 1e-10; | |
$previous: 0; | |
$current: $value; | |
@while abs($current - $previous) > $precision { | |
$previous: $current; | |
$current: 1 / $n * (($n - 1) * $previous + ($value / pow($previous, $n - 1))); | |
} | |
@return $current; | |
} | |
// Calculates luminance of a color based on the WCAG2 standard | |
// Luminance calculation based on: https://www.w3.org/TR/WCAG20/#relativeluminancedef | |
@function luminance($color) { | |
$R: red($color) / 255; | |
$G: green($color) / 255; | |
$B: blue($color) / 255; | |
@if $R <= 0.03928 { | |
$R: $R / 12.92; | |
} @else { | |
$R: nth-root(pow($R + 0.055 / 1.055, 24), 10); | |
} | |
@if $G <= 0.03928 { | |
$G: $G / 12.92; | |
} @else { | |
$G: nth-root(pow($G + 0.055 / 1.055, 24), 10); | |
} | |
@if $B <= 0.03928 { | |
$B: $B / 12.92; | |
} @else { | |
$B: nth-root(pow($B + 0.055 / 1.055, 24), 10); | |
} | |
@return $R * 0.2126 + $G * 0.7152 + $B * 0.0722; | |
} | |
// Calculates the contrast of two colors based on the WCAG2 standard | |
// Constrast calculation based on: https://www.w3.org/TR/WCAG20/#contrast-ratiodef | |
@function contrast($color1, $color2) { | |
@if luminance($color1) > luminance($color2) { | |
@return (luminance($color1) + 0.05) / (luminance($color2) + 0.05); | |
} @else { | |
@return (luminance($color2) + 0.05) / (luminance($color1) + 0.05); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment