Fixing and Scrolling Background Images

You can have your background image fixed to the browser's viewport, or allow it to scroll along with the document by using the background-attachment property along with a value of either fixed or scroll.

Typically, this is used for either the entire body or content areas within the document. However, as you've seen so far, you can use it in any element where it makes sense to do so.

Consider the following rule:

body {background-image: url(arrows.gif); background-position: right; background-repeat:
 no-repeat; background-attachment: scroll;}

Here, I've attached a background image, positioned it to the right with no repeat, and scrolled the background. This actually creates a rule that mimics default browser behavior, which is to scroll the background with the content (see Figure 8-11).

Figure 8-11. When a background graphic is set to scroll, it scrolls along with the element to which it's attachedin this case, the body.

Now, if you were to write the same rule with a value of fixed, the results would be quite different (see Figure 8-12).

Figure 8-12. No matter where I scroll, the background image remains fixed in this case.

You can achieve a range of interesting effects using scrolling with backgrounds. Of course, you'll want to try it for yourself, to really see how scrolling works in a browser. Try a range of options: Set the image to repeat, for example, or position your image in different locations and try out both the fixed and scroll values to compare how each works.


Some accessibility advisors suggest that using scrolling text over backgrounds is more difficult to see. I know this much: I get motion sensitivity fairly easily, and if I'm trying to scroll through text over a textured background, it will make me a little woozy. So use this technique with care!