DekGenius.com
Previous Section  < Day Day Up >  Next Section

Recipe 2.7 Fixing the Background Image

Problem

You want a background image to remain in the browser window, even as the user scrolls down a web page.

Solution

Use the background-attachment property set with a fixed value, like so:

body {
 background-image: url(bkgd.jpg);
 background-repeat: no-repeat;
 background-attachment: fixed;
}

Discussion

By using this technique, you are locking down the background image. So, even if a visitor scrolls, the image remains where you placed it originally. Another acceptable value for background-attachment is scroll, which is the default value. So, even if you don't specify scroll, the background image moves up with the rest of the document as the visitor scrolls down.

For example, imagine you want to post on your web page a photo of a recent trip, and you want the photo positioned on the left side of the page and your text on the right. As the reader scrolls down to read more about the trip, the photo from the trip stays in place, as shown in Figure 2-15. Here's the code:

body {
 background-image: url(bkgd2.jpg);
 background-repeat: no-repeat;
 background-attachment: fixed;
 background-position: -125px 75px;
 margin: 75px 75px 0 375px; 
}
h1, h2, h3 {
 padding-top: 0;
 margin-top: 0;
 text-transform: uppercase;
}
p {
 text-align: justify;
}

Figure 2-15. The photo staying in place as the visitor scrolls
figs/csscb_0215.gif


To take this further, you can lock down the image on block-level elements other than body. For example, try the heading elements when designing a review for a movie or concert. The following CSS rule can create the interesting surfing experience:

h1, h2, h3 {
 font-size: 200%;
 background-image: url(bkgd2.jpg);
 background-repeat: no-repeat;
 background-attachment: fixed;
 background-position: center;
 padding: 1.5em;
 text-align: center;
 color: white;
}

Because of the padding and light color on the headings, there is enough room to see the background image "through" the elements as well as to read the headlines. As the visitor scrolls the web page reading the review, she will see the rest of the image, as shown in Figure 2-16.

Figure 2-16. The photo coming through the headings instead of the body element
figs/csscb_0216.gif


At press time, only Mozilla and Netscape 6+ supported the application of background images as fixed attachments to block-level elements like header elements used in this Solution. Internet Explorer 5.x and 6 for Windows repeat the background image in each header element.

See Also

Recipe 2.6 to position a background image; Recipe 10.5 for a hack to fix Internet Explorer for Windows' lack of support for background-fixed; the CSS 2.1 specification for background-attachment at http://www.w3.org/TR/CSS21/colors.html#propdef-background-attachment.

    Previous Section  < Day Day Up >  Next Section