Tuesday, 14 June 2011

How to use sprites for web graphics and buttons

This is an important technique to create web icons, buttons and interface elements for your web site.  Essentially all the small web graphics, rollover states and other background images that you use are consolidate into one single graphic called a sprite. You can then use CSS to display just the bit of the graphic that you want at any position and time.
This is an example of part of the yahoo sprite.

What's the point in using one big image, why not have multiple smaller images?
The main reason for this is to improve web performance - SPEED!
Each separate image file that you use makes it's own server request.  For numerous small images the number of server requests and responses increases  both time and bandwidth.

Here are examples of some famous sprites, notice how they are usually PNG files because they have transparent backgrounds:



How do you specify just part of the sprite?
This is done easily with CSS.  Take this example of three orange icons in one PNG file. Each icon is 32x32px so they fit into an image that is 96 x 32 pixels.

To specify the three different button images we use the following CSS:
.home { width:32px; height:32px; background:url(orangeiconsprite.png) 0 0;}
.mobile { width:32px; height:32px; background:url(orangeiconsprite.png) 32 0;}
.exit { width:32px; height:32px; background:url(orangeiconsprite.png) 64 0;}

and then apply them to the element we want.
There are some more easy examples over at w3schools of how to apply CSS to your sprites.

So how do you make your sprites?
Just open your fav image editing software and drop all your images into one file.  Remember that you will have to reference the exact location of each image so I usually set up a grid (like the one above that was on a 32 pixel grid)

In photoshop you can create a grid by going into:
Preferences> Guids,Grids>
and select the following

Then choose View> Show> Grid

Online Sprite Making Tool
Another way to make sprites is to use an online resource like  http://css-sprit.es/
This website lets you upload individual files, which it outputs as a single image along with the CSS code AND allows you to use CSS rollover effects mmmmh nice!

For more details about using the sprites in links, buttons and hover effects check out www.csscody.com/css/css-sprite/494/

Interested in web graphics?  Then check out the following Web Devil posts:


Share/Bookmark

1 comment:

  1. I have bookmarked this link as it is very educational, my kids will be following this post too.
    web design in karachi

    ReplyDelete