# Relative color luminance

This is a method for calculating color luminance about which Lea Verou gave talk at the Smashing conference. It enables you to dynamically pick appropriate colors in a way the text remains readable to the human being. Full explanation of the formula is at w3.org.

The procedure goes as follows:

1. Calculate luminance for text and background
2. Calculate the contrast ratio using the following formula. (L1 + 0.05) / (L2 + 0.05), where L1 is the relative luminance of the lighter of the foreground or background colors, and L2 is the relative luminance of the darker of the foreground or background colors.
3. Check that the contrast ratio is equal to or greater than 4.5:1

The key to it all is to retain proper contrast ratio between foreground and background color luminance.

Here is the actual function that returns the relative luminance of the color:

``````// color array - [r,g,b] , each color with value ranging from 0 to 255
// @return int - number [0-100], describes relative luminance of the color,
//          0 represents the luminance of completely black while
//          100 represents the luminance of the white color.

function luminance(color) {
var rgb = color.map(function(c) {
c /= 255 // to 0-1 range
return c < 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4)
})

return (
21.26 * rgb + // red
71.52 * rgb + // green
7.22 * rgb
) // blue
}
``````

To test it right now you can open up a browser’s console, paste the function and try to use it right away.

Cheers!