Better Foreground Sprites

A while ago I wrote about using CSS Sprites in img tags, calling it Foreground Sprites. Thus you avoid performance-eating HTTP requests, but the page turns really ugly when CSS is switched off because the sprite image will be displayed in its full size.

What are the alternatives? Using background-images with off-screen text? Bad code:

<a href="foo" class="button">

<span>Alternative Text</span>

</a>

a.button, button {

background: url(foo.gif) 0 −26px no-repeat;

display: block;

height: 52px;

overflow: hidden;

position: relative;

width: 150px;

}

span {

left: −9999px;

position: absolute;

top: auto;

}

That’s a bad idea with accessibility issues. Screen readers will be able to read the text, but if somebody with low vision has high-contrast custom stylesheets, it is likely that the background-image won’t be displayed. Still the alternative text will be invisible off-screen, so the link or button becomes unusable.

A better solution

Now Google’s accessibility specialist T.V. Raman explained their idea for replacing images with sprites. Here are screenshots of Google search results with images, and with background images disabled:

Google puts the alternative text behind the background image simply by attaching it on the span element, not the anchor. So when CSS or background images are turned off, the text just reappears.

<a id="logo" title="Go to Google Home" href="http://www.google.com/">

Google

<span></span>

</a>

#logo {

display: block;

height: 52px;

overflow: hidden;

position: relative;

width: 150px;

}

#logo span {

background: url(foo.gif) 0 −26px no-repeat;

height: 100%;

left: 0;

position: absolute;

top: 0;

width: 100%;

}

There’s only an issue if you have a lot of alternative text, perhaps combined with text zoom, so that it doesn’t fit in the reserved space. But I can live with that.

Congratulations to Google for this ellegant solution, and it’s so simple! Why didn’t I think of it?

Will, thanks for the hint. There were indeed people describing this technique five years ago! That explains why this technique can be found in a combination with terrible table layout within the Google search results page. Strange that they waste an incredible amount of bytes, hardware, and energy by using antiquated templates.

As a side effect I should note that you can also use this technique to set a background color for the span and apply some opacity. That fixes the problem of inherited transparency on the text when your designers just want the background to be transparent.