CSS Sprites for Beginners

A lot of people who are new to modern web development concepts are not introduced to this technique early on in their education, whether school- or self-taught.

In short, sprites:

  • decrease the number of http requests to your server by combining the majority of your image assets
  • remove the flicker that occurs using older methods of creating hover effects

Here is a screenshot of the transparent .png we are going to be using for our button:

Here is the code to set this up:

a.button {
 width: 152px;
 height: 152px;
 display: block; /* setting anchors to display 
 block forces the width and height properties.*/
 background-image: url('http://nerdwith.me/tutfiles/
 background-repeat: no-repeat;
 background-position: -13px -12px;
a.button:hover {
 background-position: -204px -12px;

Here is the HTML for the anchor tag:

 <a href="http://nerdwith.me" class="button"></a>

Hover over me:

Breaking this down is very simple. The top left of your image is 0px 0px, the first number being the x axis (or the left-to-right) and the second number being the y axis (or the up-and-down). In order to get an image sprite to look properly, you have to set the background position property in your CSS to the appropriate negative x and negative y coordinate.

The easiest way to figure out these numbers is to open up your sprite in Photoshop. Click on Window, then Info. From the Info panel, you’ll be able to see the size of your measurement with the marquee (selection tool). Take your selection tool and start from the top left of the document. Drag the pointer from the top left of the document to the top left edge of the first image in the sprite. The measurements in the Info panel will give you the x and y coordinates to use for your sprite. Just make them negative numbers when you apply them to your CSS.

.button {
 background-position: -10px -30px;
Aug 23, 2011

Leave a comment