Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Determining Ideal Text Color Based on Specified Background Color

8 May 2007 1  
A method for programatically determining the appropriate foreground color based on the specified background color

Introduction

Here's a little snippet for everyone that develops web pages. Today, my boss told me that the text color on a web page element did not contrast enough with the element's background color. Well, she changes her mind more often than Bush denies that Iraq is in the middle of a civil war. For that reason, we had to come up with a way that would preclude us from revisiting the code when she changes her mind about the background color.

Here's a link to an article that describes the VBScript version. I kept them separate (versus putting everything in the same article) so that a search of the appropriate code category would help you find the desired version a little faster.

The Snippet

We spent three hours trying different methods to determine whether or not the text in a HTML element should be black or white. Finally, we found a W3C compliant formula for weighting the lightness of a given color. Once we found that, the rest was fairly easy.

To determine the text color, we subtracted the bgDelta value from 255, and then tried arbitrary threshold values until the text was coming up in a reasonable color for all of our test cases. Your threshold may vary, so don't hesitate to change the value we're using.

using System.Graphics.Drawing;

public Color IdealTextColor(Color bg)
{
    int nThreshold = 105;
    int bgDelta = Convert.ToInt32((bg.R * 0.299) + (bg.G * 0.587) + 
                                  (bg.B * 0.114));

    Color foreColor = (255 - bgDelta < nThreshold) ? Color.Black : Color.White;
    return foreColor;
}

We put this function into a base class that is inherited by all of the pages on our site. If you're writing VB code, you should be able to easily port this to your site.

Disclaimers

This article is short because there's really nothing of any complexity associated with the method described herein. There's also no downloadable code because - well - this is all the code, and I'm not going to fight with VS2005 just to create a sample program for you to download.

Hopefully, it will save you a little time...

History

  • 08 May 2007 - included a link at the top of this article to the VBScript version of this article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here