Html & CSS

CSS Sprites

Sprite is nothing but one image which has collection of small images that are required in web application. Which improves page loading time by reducing number of requests to server.

Why sprites

Consider one scenario , suppose we have two web pages,
1. first page shows 100 small images 1kb each
2. second page shows 1 big image of 100kb

What do you think , which page will get loaded first?
Now you may think that both pages will take same time as both pages has same page size (i.e. 100kb each), right??
Then your are wrong, second page will load first as compared to first page.

Because to fetch each resource, browser sends a HTTP-Request to server. that means to fetch 100 images browser needs to send 100 HTTP-Requests to server. Which increases page loading time so decreases performance of site.

CSS sprites reduce HTTP requests and the loading time of pages.
This is the main reason why CSS sprites are often used on websites with heavy
traffic.Particularly sprites are used for navigation (such as for hover effects), icons and buttons.

How to Use

Step 1. Creating sprite
To create sprite we can use any software like Photoshop, paint or fireworks etc.
Combine all images, icons into single images , keep some space (min. 1px ) between images as below,
sprite

Step 2. Creating CSS

Create common CSS class which applies background image to elements, As

ul#menu li a
        {
            background-image: url(sprite.gif);
        }

Now here comes the best part. To show particular image for class, we have to set
background-position correctly.
for that we have to make every image inside the sprite move to the top left corner (0px in X, 0px in Y) as that is the point where image start seeing.

To see about image button,
sprite1

ul#menu li a.about
        {
            background-position: -143px -4px;
        }

Step 3. Creating HTML

<ul id="menu">
<li><a href="#" class="home">Home</a></li>
<li><a href="#" class="about">About</a></li>
</ul>

Leave a comment