CSS Tip #2 - Accessible Image Replacement Technique

Sometimes you need to use fancy fonts to represent a title or name a section on your web site and the usual bunch of browser-available fonts won’t do, because it is too limited. Traditionally you would create a good looking image in a graphics program and include it into the code as an image and append an alt attribute to it containing the title itself. While this is probably the most straightforward way of doing it, it has several disadvantages:

  1. Images do not scale when you increase the text size
  2. With images disabled in the browser, the meaning of the graphics gets lost most of the time, the alt tag helps of course, but is often not enough.
  3. Somewhat related to the previous point, to the browser an image is just that — an image. It does not convey any information on what it represents, like for example, an html title element (h1, h2, h3, …) does.
  4. Graphics-based text is not searchable.
  5. Graphical text is not selectable.


To get around this problem, many techniques have been created (Fahrner Image Replacement, Leahy/Langridge Image Replacement, Mike Rundle’s Text-Indent Method, …), but the one that stuck with me is the so called Cover-up Method coinvented by both Petr Staníček and Tom Gilder, which takes an empty span element to literally cover the text with the image we want to show. The method is pretty simple, so here we go with the code.

This is our title represented by an h1 element and we’ve placed an empty span element in there, which we’ll use later to cover the title with the actual image.

<h1 id="title">Title<span></span></h1>

And here is all the CSS we’ll need to complete our super-beautiful and super-accessible masterpiece. ^^

h1#title {
    position: relative;
    padding: 0;
    margin: 0;
    width: 130px; /* image width */
    height: 100px; /* image height */
    overflow: hidden;
}

h1#title span {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    padding: 0;
    margin: 0;
    width: 130px; /* image width */
    height: 100px; /* image height */
    background: url(title.gif) top left no-repeat;
}

Basically, what we are doing here is taking an image (title.gif), which in our example is 130px wide and 100px high and applying it as a background image to the span. To put the span above the text, we need to increase its z-index value, and size it to fit the background in. To avoid the text from reaching out from behind the image when resized, we also set “overflow: hidden”. The rest of the code should be self-explanatory, like resetting default margins, padding, etc.

CSS Tip #2 - Accessible Image Replacement Technique Sample Files

Be good.