How to use sprites with my Image Replacement technique
This article was first published on tjkdesign.com (08-11-2006).
CSS Sprites
This is about replacing a few images with a single one to reduce HTTP requests; but rather than positioning a background image (CSS Sprites: Image Slicing’s Kiss of Death), we are positioning the IMG element used with this technique.
If you don't know about this particular solution yet, you can read this article and check examples of the original technique (demo 1, demo 2, demo 3, demo 4, demo 5).
Markup
If I do not use an ID on the first heading below it is because to position this image, we can simply rely on default top and left values (0, 0).
The width and height attributes are used to make sure we do not show the image unless there is CSS support.
<h2><img src="tip_sprite.gif" alt="" width="0" height="1" />CSS Sprites</h2>
<p>...</p>
<h2><img id="markup" src="tip_sprite.gif" alt="" width="0" height="1" />Markup</h2>
<p>...</p>
<h2><img id="css" src="tip_sprite.gif" alt="" width="0" height="1" />CSS</h2>
<p>...</p>
<h2><img id="image" src="tip_sprite.gif" alt="" width="0" height="1" />Image</h2>
<p>...</p>
CSS
position:relative is used to create a "reference point" for positioning each image inside its parent container (h2). The dimensions, with the overflow:hidden declaration, creates a window through which we'll display the image.
position:absolute with a top and left value move the image inside that "window".
We also set the size of the image to overwrite the width and height values in the markup.
h2 {
position: relative;
width: 300px;
height: 45px;
overflow: hidden;
}
h2 img {
position: absolute;
width: 700px;
height: 202px;
}
#markup {
top: -165px;
left: -575px;
}
#css {
top: 0;
left: -627px;
}
#image {
top: -166px;
left: 0;
}
Image
Below is the single image containing our five headings.
![]()
Things to consider
- The text is not positioned off-screen, hence it is accessible in visual browsers with images "off".
- The
altattribute's value is empty, so there is no redundancy in Assisitive Devices nor visual User Agents (when images are replaced withalttext). - The other advantage of using images in the markup rather than background images is that
imgelements appear on printed documents.