How to pick good contrast RGB colors programmatically


Suppose, in your program:

  1. color A is a color we randomly select

  2. Knowing color A, how can I pick a color B that will be in high contrast with color A?

The problem can be further reduced to: "imagine 2 squares filled with color next to one another. It should be unambiguously clear to a human eye that colors are not the same"


  • Black –> White
  • Blue –> White

Best Solution

There is some information in the Web Content Accessibility Guidelines (WCAG) 2.0 (

  1. Visual contrast:

  2. Contrast ratio:

  3. Relative luminance :

There's a good example in this site but he calculate where two colors are enough, not how to get them.

To choose a color with good contrast, I'd go with complementary colors: for example, choose the random color A, transform it to a HSV space, get the complementary hue.

Complementary hue: after you transform color from RGB to HSV, complementary hue will be 180 degrees appart (or 0.5, in a 0-1 normalized hue value). This site has something about it in PHP

Related Question