Background Images

The visual richness of CSS-based design, exemplified at the css Zen Garden, is achieved through the use of the background-image property. Used carelessly, background-image can seem more like a weapon than a design tool, as its default properties merely tiles an image horizontally and vertically on the page. But with a few simple, additional properties, background-image can be easily and elegantly controlled.

XHTML <img /> or CSS background-image?

Because images can be loaded with XHTML using the <img /> tag, it can be confusing at first to decide whether or not to use CSS's background-image property. But again, the XHTML document is structure and content, and CSS is presentation. If the image is content, i.e., it gets referred to in the text and would remain there even if the rest of the design changed entirely, go with the <img /> tag. All images supporting the design of the page, then, are loaded in CSS using background-image.

Controlling Background Images

The CSS property for loading background images is, of course, background-image, and it takes a URL as its value. In this example, an image will be tiled across the entire page:

body { background-image: url('tiledimage.jpg'); }

However, we can also tell CSS to restrict image tiling to either the horizontal or vertical dimensions of the page. Here it's helpful to remember your Cartesian coordinate plane from high school geometry: to repeat something horizontally, we refer to the x-axis; vertically, we refer to the y-axis.

For example, to tile an image down the left side of the page, we'd have:

body { background-image: url('tiledimage.jpg'); background-repeat: repeat-y; }

To tile horizontally across the top of the page, we'd replace the repeat-y value with repeat-x. If we wanted an image to appear only once, we'd use the no-repeat value.