Imagine you have to find a color that looks good both on black and white. By "looking good" I mean conforming at least WCAG AA Contrast (Minimum), which is a ratio of 4.5:1.
tl;dr: Scroll to the end to get the list of colors
The WCAG contrast ratio definition says:
(L1 + 0.05) / (L2 + 0.05), where
- L1 is the relative luminance of the lighter of the colors, and
- L2 is the relative luminance of the darker of the colors.
Contrast ratios can range from 1 to 21 (commonly written 1:1 to 21:1).
Simple math, right? You take two values and divide them.
The WCAG relative luminance definition says:
the relative brightness of any point in a colorspace, normalized to 0 for darkest black and 1 for lightest white
For the sRGB colorspace, the relative luminance of a color is defined as L = 0.2126 * R + 0.7152 * G + 0.0722 * B where R, G and B are defined as:
- if RsRGB <= 0.03928 then R = RsRGB/12.92 else R = ((RsRGB+0.055)/1.055) ^ 2.4
- if GsRGB <= 0.03928 then G = GsRGB/12.92 else G = ((GsRGB+0.055)/1.055) ^ 2.4
- if BsRGB <= 0.03928 then B = BsRGB/12.92 else B = ((BsRGB+0.055)/1.055) ^ 2.4
and RsRGB, GsRGB, and BsRGB are defined as:
- RsRGB = R8bit/255
- GsRGB = G8bit/255
- BsRGB = B8bit/255
Don't get bamboozled by the equations, it's still simple math! The last three lines are just about normalizing the color channels by dividing them with 255, here are some examples:
Then getting the R, G, and B values is done by a simple division (divide by 12.92) if the normalized value is less than or equal to 0.03928, or applying the exponential formula above if the normalized value is greater than 0.03928. The final step is summing these three values with different weights.
It's not hard to see that the relative luminance of black is 0, and white is 1. Calculating their contrast ratio gives (1 + 0.05) / (0 + 0.05) = 21. We can calculate any other color's contrast ratio against black and white by the following (where "c" is the color's relative luminance):
- against black: (c + 0.05) / (0 + 0.05)
- against white: (1 + 0.05) / (c + 0.05)
We have a requirement of a contrast ratio of at least 4.5, therefore:
- against black: (c + 0.05) / (0 + 0.05) >= 4.5
- against white: (1 + 0.05) / (c + 0.05) >= 4.5
Solving the two inequalities give:
- against black: c >= 0.175
- against white: 0.1833 >= c
In the end we get the relative luminance requirement of:
0.175 <= c <= 0.1833
Finally, I created a pen which iterates through the RGB color space, from black to white with increments of 0x11 = 17 per channel. Iterating through all of the colors would take some time and CPU, and I'm sure listing ~300k colors wouldn't be practical. So the pen iterates through the colors which can be described with 3-digit hexa notation, and lists 76 colors that matches our requirements. Use them wisely ;)