Add to Technorati Favorites

adbits - tell the world

Using CSS Image Sprites

Votes: 432

Lets go over the history of the sprite first.

History 

 Google has some good definitions here , nevermind the ones about fairys and such, those aren;t the sprites we are dealing with here. 

"Sprites were originally invented as a method of quickly compositing several images together in two-dimensional video games using special hardware. As computer performance improved, this optimization became unnecessary..." - Wikipedia

How can we use this? 

Ever want to do image css rollovers? like in the css list navigation. The problem is, when you goto rollover the link, it hesitates the first time, because it has to load the a:hover background image live. Yes there might be other ways, but that involves more code, this is a sleek and simple way to "preload" your rollovers.

Lets see some examples

Html 

<a href="#">Sprites are so 2007</a> 

CSS

a {
    display: block;
    height: 15px;
    width: 390px;
    font-size: 12px;
    font-family: Arial, Helvetica, sans-serif;
    text-decoration: none;
    color: #333333;
    background-image: url(sprite.gif);
    background-position: 0px -25px;
    padding: 5px;
}
a:hover {
    background-position: 0px 0px;
}

Sprites are so 2007

How it works

The trick is, you make a "viewing window", in this case, 25px high and 400px wide.  but the image is 50px high and 400px wide, so you see it,s 2 images in 1.

So to make it work you offset the image on a:hover, in this case by 25px, another good thing to remember is, you can use negative numbers, as I do here.

We hope this helps, although we don't use it here at Webbake, yet. Download it!

Write a comment

  • Required fields are marked with *.

If you have trouble reading the code, click on the code itself to generate a new random code.
Security Code: