HEMANT SONKER’S BLOG

January 13, 2009

CSS Sprites

Filed under: HTML, css — Hemant Sonker @ 5:28 pm

CSS sprites are a way to reduce the number of HTTP requests made for image resources referenced by your site. Images are combined into one larger image at defined X and Y coorindates. Having assigned this generated image to relevant page elements the background-position CSS property can then be used to shift the visible area to the required component image.

So how it is done?

This technique can be very effective for improving site performance, particularly in situations where many small images, such as menu icons, are used. The Yahoo page or msn home page, for example, employs this technique.

Let’s start by showing the traditional way of making the list as navigators. Notice in the CSS below how the anchor tag does not get a background-image, but each individual class does.

#nav li a {background:none no-repeat left center}
#nav li a.item1 {background-image:url(‘../img/image1.gif’)}
#nav li a:hover.item1 {background-image:url(‘../img/image1_over.gif’)}
#nav li a.item2 {background-image:url(‘../img/image2.gif’)}
#nav li a:hover.item2 {background-image:url(‘../img/image2_over.gif’)}
.
.
.and so on

example1before

Using CSS Sprites, we can really lighten this example up. Instead of having ten separate images for the buttons (five default states and five rollover states), we can literally combine all of them into one big long image. I won’t go into great detail about how this is done, I’ll just give you a basic walkthrough. Create a new image that is as wide as your widest image and and as tall as the combined height of all your images plus X pixels, where X is the number of images you have. Now place you images into this new image, left aligned, one on top of the other with one pixel of white space in between.

Now check out by using css sprites example. Notice in the CSS that there is a single background-image applied to the anchor element itself, and the unique classes merely shift the background position with negative Y coordinates.

#nav li a {background-image:url(‘../img/image_nav.gif’)}
#nav li a.item1 {background-position:0px 0px}
#nav li a:hover.item1 {background-position:0px -72px}
#nav li a.item2 {background-position:0px -143px;}
#nav li a:hover.item2 {background-position:0px -215px;}

so on…..

example1after

We were able to reduce the number of HTTP-Requests by 9 and the total file size of the image(s) by 6.5 KB. That’s a pretty huge improvement for such a little example.

This was a small example which reduced this much size.Think about this doing on the whole website.

Please refer  Alistapart.com

too.

No Comments Yet »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.