The idea behind CSS sprites is to consolidate multiple images into one sprite and then selectively display portions of this sprite with positioning. The steps are as follows:
* Group multiple images together (usually icons or decorative images) into one sprite
* Evenly space these images, aligned into one or more lines
* Set this sprite to the background image of an element (usually a list)
* Position the sprite to display the appropriate image by shifting the X or Y position by a multiple of the spacing
* Enjoy the increased speed and reduced HTTP requests
Example
Let’s look at the html for the current example. As you can see it is very straight forward.
- Code: Select all
<div id="sprites">
<a id="top-left" href="#"></a>
<a id="top-right" href="#"></a>
<a id="bottom-left" href="#"></a>
<a id="bottom-right" href="#"></a>
</div>
The CSS
It?s time to apply the magic, and as you can see here as well, it is very simple. The magic is how we are positioning the background image in each link and every time we hover over a new link we will move the background image to a new position.
- Code: Select all
a#top-left {
background: url('apple_sprite.jpg') 0px 0px no-repeat; }
a#top-left:hover {
background: url('apple_sprite.jpg') 0px -210px no-repeat; }
a#top-left:visited {
background: url('apple_sprite.jpg') 0px -210px no-repeat; }
a#top-right {
background: url('apple_sprite.jpg') -130px 0px no-repeat; }
a#top-right:hover {
background: url('apple_sprite.jpg') -130px -210px no-repeat; }
a#top-right:visited {
background: url('apple_sprite.jpg') -130px -210px no-repeat; }
a#bottom-left {
background: url('apple_sprite.jpg') 0px -105px no-repeat; }
a#bottom-left:hover {
background: url('apple_sprite.jpg') -0px -315px no-repeat; }
a#bottom-left:visited {
background: url('apple_sprite.jpg') -0px -315px no-repeat; }
a#bottom-right {
background: url('apple_sprite.jpg') -130px -105px no-repeat; }
a#bottom-right:hover {
background: url('apple_sprite.jpg') -130px -315px no-repeat; }
a#bottom-right:visited {
background: url('apple_sprite.jpg') -130px -315px no-repeat; }