## DEV Community is a community of 664,478 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

# Relative color luminance

Luka Vidaković
Originally published at lvidakovic.com ・2 min read

C/P-ing this from my older blog posts. This one is from 2014. since I was a junior dev pretty much. Nevertheless it's astonishing how many digital products get this wrong when applying the hyped up dark mode.

This is the 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[0] + // red
71.52 * rgb[1] + // green
7.22 * rgb[2]
) // 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!

## Discussion (1)

Kevin Kirchner

Check out this color palette generator that uses a luminance-based scale: grayscale.design