Color and CSS

To use color well in CSS, you'll want to know about the various ways color can be defined. Although color can be applied using any number of properties, there are specific value options that you'll want to know about.

Hexadecimal Color

Hexadecimal (hex) is a base 16 number system, useful in computing because 8 bits (1 byte of memory) can be represented by a single number or letter. The system uses numbers from 0 to 9 and letters from a to f in any combination of six (and starting with an octothorpe) to represent the correlating red, green, and blue colors (#RRGGBB).

#FFFFFF = 255, 255, 255 = white

Any hexadecimal combination is allowed in HTML and CSS to represent color (see Example 8-1).

Example 8-1. Hexadecimal color in style

body {color: #FFCC99; background-color: #808080;}
a {color: #66CC33;}

If you applied these styles to a document, the background color would be gray, the text color peach, and the link color bright green.

Hexadecimal Shorthand

Hex shorthand enables you to shorten any hex color that has value pairs. This means that each RR, GG, and BB values have to be the same, such as #00CC33 or #888888. In hex shorthand, you take one digit from each value pair, so the results would be #0C3 and #888. In a case as in #808080, the values are not paired, so you can't make it into shorthand (see Example 8-2).

Example 8-2. Hexadecimal shorthand color

body {color: #FC9; background-color: #808080;}
a {color: #6C3;}


You can use hex shorthand in any CSS document, but not in presentational HTML.

RGB Values

Another means of representing color in CSS is using the actual RGB values. These can be found in an imaging program such as Photoshop (see Figure 8-1).

Figure 8-1. Finding the RGB values of a gray color using Photoshop.

In this case, the color would be presented using the following syntax:

color: rgb(128, 128, 128);

RGB Percentages

You can also use percentages of red, green, and blue. A 0% value is black, and a 100% value is white. So, if you set a color as follows:

color: rgb(50%, 100%, 30%);

the color applied will be a bright green.

Color Names

You can use 17 color names to describe color. The colors are aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, yellow, and orange (orange was just introduced in CSS 2.1):

color: orange;

You're probably wondering which color value type you should use. The honest answer? All of them! You'll probably find yourself using combinations of keywords, shorthand hex, and hexadecimal most frequently.


In the upcoming CSS 3.0, many additional colors have been added, but they aren't available for widespread, valid use at the time of this writing.