CSS Sprites for Drupal Themes

What is a CSS sprite? In short a CSS sprite is one big image combining all the images used in a theme or web site template. So instead of having loads of separate little images, you combine them into one.

For an example Yelvington posted a really good example of CSS Sprites - take a look at his example sprite.

So how do we use these sprite images? The secret CSS sauce is background-position. You call the image only once and then use background-position to move it around to only show the bits you want.

A real easy example is for hover effects on links. Say you have an icon that is gray, but on hover you want to show a colorized version. The old way would be to have two separate images, but that sux for performance and theres always a lag for the image to download when you first hover the link (unless you preload the images with JavaScript).

With one CSS sprite the image downloads with the page load, and background position merely shifts the colorized version into view on hover. Heres a code example:

#nav li a {
  background-repeat: no-repeat;
#nav li a:link,
#nav li a:visited {
  background-position:5px 5px;
#nav li a:hover,
#nav li a:focus {
  background-position:5px -30px;
#nav li a.active {
  background-position:5px -60px;

Note that in the above code example li a.active is correct, this is a standard Drupal class applied to active menu links.

As you might well be thinking this can take a fair amount of shagging about with the actual sprite and the CSS. However the performance benefits are great and if, like me, you stick to using a grid to position your sprite images the CSS is not that hard to figure out.

I found a pretty good example tutorial about CSS sprites here http://css-tricks.com/css-sprites/

Last updated 21st July, 2009 - 4:17pm

Authored by Jeff Burnz on