ProblemYou need to place stationary or tiled images as backgrounds for certain page elements or an entire web page. SolutionUse the CSS properties background-image, background-position, background-attachment, and background-repeat to specify how you want the background to be displayed. Background styles can be assigned to the <body> tag in a CSS stylesheet to display an image once in a fixed position: body { background-image: url(/images/backgrounds/penguins.jpg); background-position: 0px 0px; background-attachment: fixed; background-repeat: no-repeat; background-color: white; margin: 0px; } Or you can assign a CSS ID to other page elements, such as table cells or <div>'s, to display a repeating, tiled image across the item's background: #topnav { background-image: url(/images/backgrounds/topnav.jpg); background-repeat: repeat-x; } DiscussionBackground images can add an extra dimension to your design, but they also can create usability problems for your visitors. A strong, busy background can make the text that appears over it hard to read. To maintain a balance between design and readability, use an image editor to fade or otherwise restrain the impact of a photo to be used as background, while strengthening the text to appear over it with extra font weight, size, and line height. Figure 3-6 shows a web page that uses both background techniques described in the Solution. The main background (the penguins) is one large image given a fixed position at the upper left corner of the page by the stylesheet. Figure 3-6. Different backgrounds can be displayed in different areas of the pageUsing the CSS rule background-attachment: fixed the image will not move even as the visitor scrolls down the page, as shown in Figure 3-7.
For the background of the navigation bar (#topnav), I created a 1x50 pixel JPEG with a top-to-bottom, teal-to-white gradient. By default, CSS background images will repeat both horizontally and vertically. Because the row of links on my page runs along the top of the page, I used the background-repeat property to replicate the image only across the horizontal, x axis of the page. To repeat the background vertically but not horizontally, use background-repeat: repeat-y. Figure 3-7. Fixed background images stay put, even as the user scrolls down the pageSee AlsoAndrew Clover has written a JavaScript that fixes Internet Explorer's non-compliant rendering of fixed position background images. Download it at http://doxdesk.com/software/js/fixed.html. |