How to use CSS Sprite in your webpage

Many of us know this and have used it also but some people do not know what CSS sprites are. So this tip will give an idea to those people who do not know what it is.

What is CSS Sprite? It is a technique where more than images are taken, combined into one complex image and used in webpages (Simple isn’t it? ; )). The image below is an example to CSS sprite, where I have taken emoticons and created a sprite out of that.

Why to use it?

Suppose in your webpage you are using five images. You might be knowing that for every objects (javascript, image, css) used in the page, a corresponding HTTP request is made by the browser.
So for five images there will be five HTTP requests.

Instead of using 5 images if you use one sprite (which contains all 5 images) then there will be only one HTTP request.
Don’t you think it’s good? : )

How to use to? To use sprite in your website you need a sprite image.

If you have individual images then you can combine them and create a sprite image from here.

After getting the image it is very simple to use the image.
I already have a sprite image and and I will be using that image for this tip.

The trick here is to use background-position. Just use one image and by using background-position show particular portion of the image.

In the following demo, I have used three divs with size 81 * 81 (same as each image’s size). The sprite image size is 486 * 161, So if you want to use row #1, column #1 image then background-position will be 0px   0px. Similarly for (1, 2)     -81px     0px (1, 3)     -162px   0px

(2, 2)     -81px    -81px

HTML Code

     

CSS Code

.emoticon {     background: url('https://lh6.googleusercontent.com/-D8dhWvyzECg/Tti1Ce88CII/AAAAAAAAAIo/9PuGzkL3hUo/s486/SmileySprite.jpg')
no-repeat scroll 0px 0px;     height: 81px;     width: 81px; } .devil {     background-position: -81px 0px; } .cool {

Code snippet: http://jsfiddle.net/fH7LK/1/

Conclusion: .It can be used as background image only.

.You should not make a single sprite of all the images of your site. It’s not like only one sprite images can be used for site.

.You can chose images smartly to make a sprite image, e.g: Sprite for emoticon, Sprite for menu icons, etc.

150 150 Burnignorance | Where Minds Meet And Sparks Fly!