HTML5, CSS3, and JavaScript Fourth Edition

(Ben Green) #1

CHAPTER 7. COLORS 72


7.1 How To Specify Colors


There are many ways to specify colors. For webpages these include prede-
fined name, hex code, rgb code (red-green-blue), and hsl code (hue-saturation-
lightness). CMYK (cyan-magenta-yellow-black) is popular for printing but
not reliable for webpages.


These examples show different ways to set the background color to be orange.


body { background-color: orange; } / named color /
body { background-color: #FFA500; } / hex code /
body { background-color: rgb(255,165,0); }
body { background-color: rgba(255,165,0,1.0); }
body { background-color: rgba(255,165,0,100%); }
body { background-color: hsl(39,100%,50%); }
body { background-color: hsl(39,1,.5); }
body { background-color: hsla(39,100%,50%,1.0); }
body { background-color: hsla(39,100%,50%,100%); }


Names: Predefined color names are things like red, green, blue, white,
black, and gray. There are 17 standard color names in CSS 2.1, and a total
of 140 that are understood by all modern browsers. In section 7.8 (page 79)
we list all 140 of them.


Hex codesare expressed as a hashtag followed by three or six “digits” in
the hexadecimal numbering system (base 16). These numbers range from
0 (the absence of the color) through 9 and A through F, for a total of 16
different “digits.” F is the highest intensity. Using a six-digit code, red,
green, and blue range from 00 to FF for 256 possible intensities. If only
three digits are specified, each digit is treated as though it was used twice.
Thus, #123 means #112233.


RGB(red, green, blue) numbers are exactly equivalent to hex codes, but
instead of being expressed in hexidecimal they are written as a list in base



  1. The values range from 0 (no color) to 255 (total color).


RGBA(red, green, blue, alpha) is like RGB but has an additional param-
eter to controltransparencyusing analphavalue. Alpha ranges from 0.0
(transparent) to 1.0 (opaque).


HSLandHSLA(hue, saturation, lightness, alpha) are also usable on web-
pages.

Free download pdf