Chapter 39. Using Background Images on Web Pages
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. |
The browser tiles or repeats the image across all available real estate in the browser window, as in Figure 39.1.
<body background="images/ufo.gif">
Figure 39.1. When you add a background image to the page with HTML, the browser automatically tiles the image to fill the page.
[View full size image]
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);">
Listing 39.1. View Source for Figure 39.2.
<body style="background-image: url(images/ufo.gif);
background-repeat: repeat-y;">
Figure 39.2. You can specify vertical-only tiling when you use CSS for background images.
[View full size image]
Figure 39.3. Move the background image around the screen by including background-position in your style definition.
[View full size image]
Listing 39.2. View Source for Figure 39.3.
<body style="background-image: url(images/ufo.gif);
background-repeat: repeat-y;
background-position: right;">
Figure 39.4. With CSS, you can even make the background image impervious to scrolling.
[View full size image]
Listing 39.3. View Source for Figure 39.4.
To make the background image scroll with the rest of the page content, set background-attachment to scroll.
<body style="background-image: url(images/ufo.gif);
background-repeat: no-repeat;
background-position: right;
background-attachment: fixed;">
TIPThe background-attachment style definition works best with images that don't tile. |
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; |