Image for post
Image for post

How to get an accurate contrast color with Sass

It’s very common using Sass to need to get the best color for text depending on the background-color. If you are using Compass maybe you’ve notice that there is a function called contrast-color that it suppose to do this… but the true is that it fails a lot, in Frontendcore I’ve solve this with custom functions.

It’s not very difficult to do an algorithm to do this, the general idea is to get the lightness of each color and return the most “contrasty”. This is the contrast color function I’m using in Frontendcore overwriting the Compass function.

@function contrast-color (
$dark: $color-foreground,
$light: $color-background
@if $color == null {
@return null;
} @else {
$color-brightness: brightness($color);
$light-text-brightness: brightness($light);
$dark-text-brightness: brightness($dark);
@return if(abs($color-brightness — $light-text-brightness) > abs($color-brightness — $dark-text-brightness), $light, $dark); }

As you can see it’s not very different of the compass function, so… why it shoud work better than this one? To answer this we need to take a look to the brightness function, that I also overwrite:

@function brightness($c) {
$rlin: de-gamma(red($c)/255);
$glin: de-gamma(green($c)/255);
$blin: de-gamma(blue($c)/255);
@return re-gamma(0.2126 * $rlin + 0.7152 * $glin + 0.0722 * $blin) * 100; }

As you can see I’m also calling a couple of gamma functions. What they do? Let’s take a look to the de-gamma function…

@function re-gamma($n) { 
@if $n <= 0.0031308 {
@return $n * 12.92;
} @else {
@return 1.055 * pow($n,1/2.4) — 0.055;

…and of course the re-gamma function.

@function de-gamma($n) { 
@if $n <= 0.04045 {
@return $n / 12.92;
} @else {
@return pow((($n + 0.055)/1.055),2.4);

This two functions basically will compensate the gamma with which colors are actually displayed in sRGB space, ~= 2.2.

Note: This functions are calling the pow function, that is part of compass. If you are don’t want to use Compass try with MathSass

Recently it looks like Compass finally is going to update the function in future versions but comparing the new one with the one provided by Frontendcore, the goal comes to the Frontencore side.

Stop talking... how I can use it?

Checkout a real demo on codepen.

One more thing…

I really will like to be the author of this cool algorithm, but the true is that is something that the huge community of developers provide us, for free, I recommend you to take a look to this CodePen, created by @Lunelson

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store