Image Replacement Techniques

One of the more interesting applications of background-image involves using CSS to display images in place of XHTML text. For example, we might have XHTML that looks something like this:

<h1><span>Portfolio for R. U. Serious</span></h1>

The <span> tags might throw you off a bit, but we can use them in CSS to hide the XHTML text on graphical browsers, while preserving the block area taken up by the <h1> tag. So let's hide the XHTML text:

h1 span { display: none; }

(Keep in mind that, at least at present, even though the CSS has hidden the text from view, screen readers that read text aloud for visually impaired users should still read the text outloud. The only problem that this method presents is for graphical browser users who may have their browser set to not display images. We'll examine alternative style sheets in another section to account for this.)

Suppose, then, that we wanted to use the following image in place of the XHTML text:

Sample image for Portfolio for R. U. Serious

To do that, we'd need to know the exact dimensions of the image (in this example, the image is 300 pixels wide and 50 pixels tall), which will be necessary to size h1:

h1 { width: 300px; height: 50px; background-image: url('portfolio_head.jpg'); background-repeat: no-repeat; }

The background-repeat property is not necessary here, since we've set h1 to the exact dimensions of the image. However, it won't hurt anything, either. Also, we'd probably want to set padding to zero.

See a demonstration of this.