Last active
May 19, 2022 12:11
-
-
Save damianwajer/2d001a55ada6bdce18e84976d30b8dd6 to your computer and use it in GitHub Desktop.
[SASS] Set of functions to ensure safe colors | https://www.damianwajer.com/blog/scss-functions-to-ensure-safe-colors/
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
// Set of functions to ensure safe colors. | |
// Inspired by: | |
// - https://pressupinc.com/blog/2014/06/preserving-readability-variable-text-background-colors-sass/ | |
// - http://blog.benjamincharity.com/generate-safe-text-colors-with-sass/ | |
$lightness-bound: 70 !default; | |
$hue-bound-bottom: 40 !default; | |
$hue-bound-top: 200 !default; | |
$brightness-diff-bound: 40% !default; | |
@function checkColorDangerZone($color, $amount: $brightness-diff-bound) { | |
@if ((lightness($color) > $lightness-bound) or (hue($color) > $hue-bound-bottom and hue($color) < $hue-bound-top )) { | |
@return darken(desaturate($color, 70), $amount); | |
} @else { | |
@return lighten(desaturate($color, 50), $amount); | |
} | |
} | |
@function ensureSafeColor($color, $background-color: null, $amount: $brightness-diff-bound) { | |
@if $background-color == null or $background-color == transparent { | |
@return $color; | |
} | |
// Checking text lightness difference from accent background | |
$diff: lightness($color) - lightness($background-color); | |
// If low brightness difference | |
@if abs($diff) < $amount { | |
@return checkColorDangerZone($background-color, $amount); | |
} | |
// High enough contrast; @return original color | |
@else { | |
@return $color; | |
} | |
} | |
@function isDarkColor($color: $body-bg, $lightness-bound: 50) { | |
@return if(lightness($color) > $lightness-bound, false, true); | |
} | |
// Makes a light color darker or a dark color lighter depending on color lightness. | |
// @param $color [Sass::Script::Value::Color] | |
// @param $amount [Sass::Script::Value::Number] The amount between `0%` and `100%` | |
@function distinguishColor($color, $amount) { | |
@return if(isDarkColor($color), lighten($color, $amount), darken($color, $amount)); | |
} | |
// Makes a light color lighter or a dark color darker depending on color lightness. | |
// @param $color [Sass::Script::Value::Color] | |
// @param $amount [Sass::Script::Value::Number] The amount between `0%` and `100%` | |
@function strengthenColor($color, $amount) { | |
@return if(isDarkColor($color), darken($color, $amount), lighten($color, $amount)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment