Skip to content

Instantly share code, notes, and snippets.

@joneff
Created December 5, 2017 16:35
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 joneff/b9921a229fe78a0852eac306d2aadda3 to your computer and use it in GitHub Desktop.
Save joneff/b9921a229fe78a0852eac306d2aadda3 to your computer and use it in GitHub Desktop.
Functions for dealing with colors and contrast
// Assuming the following markup
// body text
// <div class="component">component</div>
// <div class="card">component</div>
// <div class="list">component</div>
$yiq-contrasted-threshold: 150;
$white: #ffffff;
$black: #111111;
@function color-brightness($color) {
$r: red($color);
$g: green($color);
$b: blue($color);
$yiq: (($r * 299) + ($g * 587) + ($b * 114)) / 1000;
@return $yiq;
}
@function color-difference($color1, $color2) {
$r1: red($color1);
$g1: green($color1);
$b1: blue($color1);
$r2: red($color2);
$g2: green($color2);
$b2: blue($color2);
$diff: (max($r1, $r2) - min($r1, $r2)) + (max($g1, $g2) - min($g1, $g2)) + (max($b1, $b2) - min($b1, $b2));
@return $diff;
}
@function test-contrast($color1, $color2) {
$delta-brightness: abs(color-brightness($color1) - color-brightness($color2));
$color-difference: color-difference($color1, $color2);
@if ($delta-brightness > 125) and ($color-difference > 500) {
@return true;
}
@return false;
}
@function contrast-yiq($color, $dark: $black, $light: $white) {
$yiq: color-brightness($color);
@if ($yiq >= $yiq-contrasted-threshold) {
@return $dark;
} @else {
@return $light;
}
}
@function use-if-contrast($color1, $color2, $dark: $black, $light: $white) {
@if test-contrast($color1, $color2) {
@return $color1;
}
@return contrast-yiq($color2, $dark, $light);
}
$body-bg: #f0f0f0;
$body-text: green;
$component-bg: $body-bg;
$component-text: use-if-contrast($body-text, $component-bg);
$card-bg: $component-bg;
$card-text: use-if-contrast($component-text, $card-bg);
$list-bg: white;
$list-text: use-if-contrast($component-text, $list-bg);
body {
color: $body-text;
background: $body-bg;
}
body {
padding: 20px;
}
.component,
.card,
.list {
margin: 10px 0;
padding: 10px;
border: 1px solid rgba(0,0,0, .1);
}
.component {
color: $component-text;
background: $component-bg;
}
.card {
color: $card-text;
background: $card-bg;
}
.list {
color: $list-text;
background: $list-bg;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment