There are two ways to add a background image to a Web page. One is to use HTML attributes. The other is to use CSS style definitions. With HTML, you get limited design options but solid reliability across browsers. With CSS, you get more design options but less reliability.
TIPBeware of background images that overwhelm the content of the page. Stick to washed-out images that don't interfere with the legibility and clarity of your text. |
In HTML, you add the background attribute to the body tag, like this:
<body background="images/ufo.gif">
The browser tiles or repeats the image across all available real estate in the browser window, as in Figure 39.1.
Cascading Style Sheets produce the same effect:
<body style="background-image: url(images/ufo.gif);">
The preceding example creates a tiling background image, exactly as in Figure 39.1. However, CSS gives you additional options to control exactly how the background image behaves, including background-repeat, background-position, and background-attachment.
Use background-repeat to control how (or if) the background image tiles, as in Figure 39.2.
<body style="background-image: url(images/ufo.gif); background-repeat: repeat-y;">
Determine where on the page the background image appears with the background-position attribute, as in Figure 39.3.
The background-attachment attribute determines how the background image responds to scrolling. Set background-attachment to fixed to make the background image resist scrolling; that is, the background image remains rooted to its position in the browser window. The page content may scroll, but the background image does not, as in Figure 39.4.
<body style="background-image: url(images/ufo.gif); background-repeat: repeat-y; background-position: right;">
<body style="background-image: url(images/ufo.gif); background-repeat: no-repeat; background-position: right; background-attachment: fixed;">
To make the background image scroll with the rest of the page content, set background-attachment to scroll.
TIP
The background-attachment style definition works best with images that don't tile. |
For your coding pleasure, Table 39.1 lists CSS options for background images.
STYLE | CONTROLS | POSSIBLE VALUES | EXAMPLE |
---|---|---|---|
background-repeat | How or if the background image tiles | repeat-x, repeat-y, no-repeat, repeat | background-repeat: repeat-y; background-repeat: repeat; |
background-position | The position of the background image inside the div | Any combination of the following: left, right, center, top, bottom | background-position: left; background-position: right bottom; background-position: center left; background-position: center; |
background-attachment | How the background image reacts to scrolling | fixed, scroll | background-attachment: fixed; background-attachment: scroll; |