CSS IMAGE SPRITES

A CSS sprite is a performance optimization technique that combines multiple images into a single image form. A web page with many images can take a long time to load and generates multiple server requests. With CSS, we can show just the part of the image we need.

Using image sprites will reduce the number of server requests and save bandwidth.

EXAMPLE

#home {

width: 46px;

height: 44px;

background: url(img_navsprites.gif) 0 0;

}

IMAGE SPRITES – CREATE A NAVIGATION LIST

We want to use the sprite image (“img_navsprites.gif”) to create a navigation list. We will use an HTML list due to the fact it can be a link and also supports a background image:

EXAMPLE

#navlist {

position: relative;

}

 

#navlist li {

margin: 0;

padding: 0;

list-style: none;

position: absolute;

top: 0;

}

 

#navlist li, #navlist a {

height: 44px;

display: block;

}

 

#home {

left: 0px;

width: 46px;

background: url(‘img_navsprites.gif’) 0 0;

}

 

#prev {

left: 63px;

width: 43px;

background: url(‘img_navsprites.gif’) -47px 0;

}

 

#next {

left: 129px;

width: 43px;

background: url(‘img_navsprites.gif’) -91px 0;

}

IMAGE SPRITES – HOVER EFFECT

Now we want to add a hover effect to our navigation list. Because this is one single image and not six separate files, there will be no loading delay when a user hovers over the image.

EXAMPLE

#home a:hover {

background: url(‘img_navsprites_hover.gif’) 0 -45px;

}

 

#prev a:hover {

background: url(‘img_navsprites_hover.gif’) -47px -45px;

}

 

#next a:hover {

background: url(‘img_navsprites_hover.gif’) -91px -45px;

}