3.6. Adding Background Images

Problem

You need to place stationary or tiled images as backgrounds for certain page elements or an entire web page.

Solution

Use 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;
	}

Discussion

Background 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 ...

Get Web Site Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.