Last Updated: February 25, 2016
·
14.95K
· deontologician

Smoothly transition from green to red

If you're ever need to generate colors on a smooth continuum from green to red, you may be tempted to treat RGB values as coordinates and do linear interpolation between them to generate intermediate colors.

This is a huge mistake.

That's because in RGB land, halfway between green and red is a gross brown color. What's that? You were expecting to go through yellow and orange in between? Sorry, RGB doesn't work that way.

The problem is that you want to change the hue smoothly (green-> yellow -> orange -> red), but you want to leave the lightness and saturation alone. Luckily, there is a color coordinate space just for you! It's called HSL (for hue, saturation, and lightness).

Hue is expressed in degrees (out of 360) and goes from red at 0deg, through green at 120deg, and finally blue at 240deg (and back to red again at 360). Easy! Best of all for us going from green to red, you're just modifying one number, with no unintended consequences.

Saturation is how "grey-scale" things are. 100% saturation means the "brightest" possible version of a color. 0% is a projection of your color on the line from black to white. Taking a picture and just changing the saturation to 0% will end up looking gray-scale.

Lightness is how washed out or blacked out the color is. Lightness 0 is black (no matter what H and S are), and lightness 100% is white. Increasing the lightness of a color makes it more "pastel", if that gives you a better intuition.

So our prototypical RGB colors in HSL are:

red: 0deg hue, 100% saturation, 50% lightness
green: 120deg hue, 100% saturation, 50% lightness
blue: 240deg hue, 100% saturation, 50% lightness

Notice that all we have to change is the hue and we dont have to worry about any dark colors or light colors happening to be in between like we do in rgb color space (since we explicitly keep lightness and saturation the same!)

So, finally, to calculate intermediate colors between green and red (going through yellow not blue), we just do:

(1 - 0.00) * 120 = 120 ( green )
(1 - 0.25) * 120 = 90 ( light green )
(1 - 0.50) * 120 = 60 ( yellow )
(1 - 0.75) * 120 = 30 ( orange )
(1 - 1.00) * 120 = 0 ( red )

Perfect!

Now for the good news, CSS3 supports colors specified in hsl. Here's an example:

p { 
    background-color: hsl(120, 100%, 50%);
}

1 Response
Add your response

Wow, you brought up a lot of lovely memories of learning Photoshop and press printing, along with the diffetrence between printer and monitor output colors. Thanks for the tip, is it directly in relation to the Pantone Color Matching system?

over 1 year ago ·