06Sep

CSS Sprites

Posted by Elf Sternberg as javascript, web development

It seems like such a stupid thing, but hey, now I know how to use CSS sprites.

Basically, it’s the same idea as a viewport slider: treat your rectangular space as a viewport onto a background image. By using the background-position attribute and the .css() control (in jQuery; there are others in other libraries), you can move the background image around. If you have two different icons of the same dimensions, you can make the DIV (or whatever rectangle you want) the same size as one of them, and concatenate all of the images together (either left/right or top/bottom). The first image will show up in the DIV. When you want the other image to show up, set the background position to the negative (left or top) of the width or height (respectively), and it’ll slide your first image out of view and show the second one.

I discovered this when I saw that Firefox was making a round-trip every time I hit the end of a paginator, because it was fetching the “enabled”/”disabled” buttons that the previous programmer had built there. A round trip for every action? My gods, you’d better save that for state control, not special effects. Anyway, it’s working now, and no more “fetches from the database” to get even a 302 (item cached) transaction.

Comment Form

Subscribe to Feed

Categories

Calendar

September 2009
M T W T F S S
« Aug   Oct »
 123456
78910111213
14151617181920
21222324252627
282930