Recipe 3.7. Creating a Stationary 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 that you want to post a photo of a recent trip on your web page, 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 (see Figure 3-12). 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 3-12. The photo staying in place as the visitor scrolls


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 (see Figure 3-13).

Figure 3-13. The photo coming through the headings instead of the body element


At press time, only Mozilla, Firefox, Safari, and Netscape 6+ supported the application of background images as fixed attachments to block-level elements like the 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 3.5 to position a background image; Recipe 11.4 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.




CSS Cookbook
CSS Cookbook, 2nd Edition
ISBN: 0596527411
EAN: 2147483647
Year: 2006
Pages: 235

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net