DEV Community

Cover image for The formula that produces color contrast
Ayyash
Ayyash

Posted on • Originally published at garage.sekrab.com

The formula that produces color contrast

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'; 
}
Enter fullscreen mode Exit fullscreen mode

In less CSS, use the contrast function:

.fcolor(@c){
   color:contrast(@c,#242424,#ffffff,43%);
}
.myclass {
  background-color: red;
  .fcolor(red);
}
Enter fullscreen mode Exit fullscreen mode

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:

Resources:

Top comments (0)