DEV Community

Cover image for The formula that produces color contrast
Ayyash
Ayyash

Posted on • Originally published at garage.sekrab.com

3 1

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:

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay