What is the best way to determine the best color for a text that will have good contrast and will be pleasing to the eyes (i.e. it can be either white, any shade of grey or black) with the help of JavaScript? The colors are denoted in hexadecimal.

  • The formula used can be found here: w3.org/TR/WCAG20/#contrast-ratiodef, but how to implement that with javascript is a different question that we cannot answer here. Commented Jan 15, 2018 at 8:33
  • Try using a colour contrast analyser (such as this developer.paciellogroup.com/resources/contrastanalyser) to ensure that your colours are going to have sufficient contrast for users with low vision and/or colourblindness. Other than that it's down to your 'corporate style' and how colour is used throughout the product in general. In answer to the JavaScript question: this is not a development forum - maybe you should try over at stackoverflow.com Commented Jan 15, 2018 at 8:34

2 Answers 2


Don't get fooled into thinking that you need to find the best shade of grey to use.

Given any background color, the foreground color that provides the highest contrast ratio will be either white or black, and not some shade of grey in between.

Having said that, pure black or white can seem a little harsh and less pleasing to the eyes - too much contrast can be quite distracting for some users. So, assuming for the purposes of this answer that black means off-black (eg #101010), and white means off-white (eg #f0f0f0), the question then becomes "is black or white better for my background color"?

In another answer I go into more detail with some good example screenshots of how contrast ratio varies for ranges of backgrounds.

In summary, for any two given colors there is a formula for contrast ratio:

The contrast ratio is calculated as (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.

In your case you simply need to calculate the contrast ratio for white and your bg color; and again for black and your bg color, and then pick black or white depending on the highest contrast ratio.


'Pleasing to the eyes' is very subjective.

But there are a lot of contrast tools like http://leaverou.github.io/contrast-ratio/ and https://contrastchecker.com which take in to account brightness contrast as well as hue contrast. Many of these tools are based on WCAG guidelines which makes them fairly standardized in their outcomes, and therefore widely used and accepted.

Not the answer you're looking for? Browse other questions tagged or ask your own question.