Go

Share Reddit Twitter Pinterest Facebook Google+ StumbleUpon Tumblr Delicious Digg Extending CSS Spriting

December 5, 2008

CSS Spriting is a technique for speeding up the load times for your website by reducing the number of HTTP requests for images to the server. On Yahoo's best practices website, they say:

"CSS Sprites are the preferred method for reducing the number of image requests. Combine your background images into a single image and use the CSS background-image and background-position properties to display the desired image segment."

This technique can be extended for non-background images on your site as well. However, some issues arise when you use CSS spriting for your main navigation elements(among other images):

  1. You can't attach alternate text to divs for accessibility purposes
  2. CSS Spriting and the IE6 PNG fix are incompatible
  3. The images will not print out on printouts unless the client option to print background images is selected (this is bad for logos and menus, etc)
  4. For images in pages (that are not actually background images), it seems semantically bad to hide the image in CSS.

With these concerns in mind, I devised a cross-browser compliant solution that addresses all of the aforementioned problems. The new technique uses an image tag, a div, and the CSS clip property.

Here's the code for the technique:

The CSS
.menu-about { width: 106px; height: 29px; position: relative; top: 0; left: -293px; }
   .menu-about img { position: absolute; clip: rect(0 399px 29px 293px); }
 
The HTML
<div class="menu-about">
     <img class="transparent_png" src="/media/1010/company-menu.png" alt="About" title="About Us" width="611" height="39" /></div>

And here's the code in action: [ view the full image ]

About

And here's an alternate solution using the anchor tag:

Contact

This technique can be easily customized in many different ways. However, for repeating backgrounds and css mouseovers, the traditional CSS sprite techniques are better suited.

Update: As Dan pointed out in the comments, this technique can accomplish css mouseovers (I overlooked this possibility since my first draft of this article only used divs, rather than anchor tags). Thanks, Dan!

CSS