HTML and CSS

Adding Color to Backgrounds

Adding color to backgrounds is extremely easy and very useful. You can add color to your page background and any element background.

Color and the Document Background

Color is added to the document background by selecting the body element and using the background-color property and a color property value:

body {background-color: #999;}

Here you see I've chosen a background of dark gray to the entire body. When viewed in a browser, this turns the background color completely gray (see Figure 8-2).

Figure 8-2. Applying color to a document background.

NOTE

You should always set a page background color, even if you intend to use graphics and other element backgrounds in your design. This is because colors are interpreted by browsers very quickly and render before any graphics, providing a more streamlined visual experience for your visitors.


Color and Element Backgrounds

With CSS, you can add color to individual element backgrounds. To do this, simply select the element and create a rule. I'll do this for the H1 as I build a style sheet for our simple document:

body {background-color: #999;}
h1 {background-color: #ccc;}

Figure 8-3 shows the H1 element with the background color added.

Figure 8-3. Adding color to the h1 element background.

I'll go ahead and add rules for the paragraph and anchor element color, too (see Example 8-3).

Example 8-3. Document and background elements with color added
body {background-color: #999;}
h1 {background-color: #ccc;}
p {background-color: #fff;}
a {background-color: #ccc;}

Figure 8-4 shows how the background color is applied.

Figure 8-4. Background colors as applied to the document and element backgrounds; note that the element background colors stretch to the full width of the element.