Sekrab Garage

Color contrast function

The formula that produces color contrast

CSS February 1, 21
Subscribe to Sekrab Parts newsletter.

Contrast is not easy. Finding out what the best foreground color to match the background color though, has a formula. Found it on CSS-Tricks:

var rgb = [255, 0, 0]; 
function setForegroundColor() { 
  var sum = Math.round(((parseInt(rgb[0]) * 299) + (parseInt(rgb[1]) * 587) + (parseInt(rgb[2]) * 114)) / 1000); return (sum > 128) ? 'black' : 'white'; 

In less CSS, use the contrast function:

.myclass {
  background-color: red;

According to WCAG (Web Content Accessibility Guide), the perfect ration for contrast is 4.5 (AA), or 7 (AAA). To see how that affects each color, use Chrome DevTools contrast checker.

So now you know why blue, was always the best choice for link colors on white backgrounds: