Calculating Color Contrast with Sass
Recently, I found out about the YIQ color space when I was reading through this 24ways article. I decided to write a Sass mixin to determine whether the ‘color’ attribute should be light or dark based on the current background color. This method is better than comparing half the value of white (i.e., 0xffffff/2) because each value in the RGB spectrum affects our eyes (rods and cones!) differently.
Well, this is the part you came for right? Let’s dig in:
The color functions red(), green(), and blue() grab the corresponding value of the color that is passed to it. We then convert these to YIQ and check the halfway point (128) and determine the color from there.
You can view a demo on codepen.
Being color blind myself, colors and contrast don’t come very easy to me. I use this mixin everywhere possible to help me determine colors from a scientific approach, rather than rely on my faulty eyes.