Image replacement

CSS image replacement is a powerful way to turn well thought out markup into pixel perfection. Image replacement is also required for some implementations of image sprites, an important technique for improving web performance in current browsers.

Unfortunately, most image replacement techniques have the downside that they are not accessible to users who have CSS support but images disabled.

Why should we support users who have CSS support but not images?

Well, some users will browse with this configuration to save bandwidth and or speed up browsing on slow internet connections. Images should form a part of the progressive enhancement stack, somewhere between the content and presentation layers depending on their purpose. Therefore, browsing without images should always be a viable option.

A solution

When I use image replacement, I like to use the following technique because it can still be accessible to all users:

  1. Your markup needs to contain a reference to a transparent 1x1px gif or png image.

    <h3 id="replaced-heading"><img src="displacement.png" alt="" />Replaced heading</h3>
  2. Your stylesheet can then make the replacement.

    h3#replaced-heading {
        background: transparent url(replaced-heading.png) left top no-repeat;
        display: block;
        width: 250px;
        height: 25px;
        overflow: hidden;
        zoom: 1; /* for IE 6&7 */
    }
    h3#replaced-heading img {
    	width: 250px;
    	height: 25px;
    }

The transparent image displaces the heading text outside of the h3 elements visible area (thanks to the fixed dimensions and overflow: hidden;). When images are disabled, the displacement image disappears also, allowing the original text to fall back into the h3 element’s visible area.

The downside is that superfluous markup is required to achieve this technique, but the bonus is that it is universally accessible!

Posted in

Leave a reply