Skip to content

Instantly share code, notes, and snippets.

@aaronrussell
Created January 15, 2011 16:33
Show Gist options
  • Save aaronrussell/781017 to your computer and use it in GitHub Desktop.
Save aaronrussell/781017 to your computer and use it in GitHub Desktop.
Sass function and mixin for setting contrasting background and foreground colors
$contrasted-default-dark: #000;
$contrasted-default-light: #fff;
@mixin contrasted($bg, $dark:$contrasted-default-dark, $light:$contrasted-default-light){
background-color: $bg;
color: get_contrast_yiq($bg, $dark, $light);
}
module Sass::Script::Functions
def get_contrast_yiq(color, dark = Sass::Script::Color.new([0,0,0]), light = Sass::Script::Color.new([255,255,255]))
yiq = ( (color.red*299) + (color.green*587) + (color.blue*114) ) / 1000;
yiq >= 128 ? dark : light
end
end
@import "contrast_mixin";
body {
padding: 20px;
font: bold 16px/24px Helvetica, Arial, sans-serif;
}
div {
padding: 10px;
margin-bottom: 10px;
&.a { @include contrasted(#ef4444); }
&.b { @include contrasted(#faa31b); }
&.c { @include contrasted(#fff000); }
&.d { @include contrasted(#82c341); }
&.e { @include contrasted(#009f75); }
&.f { @include contrasted(#88c6ed); }
&.g { @include contrasted(#394ba0); }
&.h { @include contrasted(#d54799); }
}
@OleMchls
Copy link

And here is the same thing in pure sass

=contrasted($bg, $dark:#000, $light:#fff)
  background-color: $bg
  $yiq: ( (red($bg)*299) + (green($bg)*587) + (blue($bg)*114) ) / 1000
  @if $yiq >= 128
    color: $dark
  @else
    color: $light

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment