How to use image sprite in html

|
| By Webner

What is the importance of image sprite in html and how these Sprite images can be used in html and css?

Image sprite is a collection of different images put into a single image. Image sprites are are used in web pages to lower down the bandwidth and the page load time.

For example, all icons in our website can be clubbed together by image sprite.

Advantages of using image sprite:

If we create a web page with many images, it can take a long time to load and generates multiple server requests.Use of image sprites will reduce the number of server requests and save bandwidth.
Image sprite improves the loading performance of the page.
Less code maintains and easier cross-browser testing.

How to use image sprite in css and html: This is a single image which is created by different small sized images or icons using any photo editing tool:

1

Suppose we have above image. Instead of using different icon images, we use this single image (“icons.png”). In the above example image, if we use 20 separate images, then http requests would be 20 and if we use image sprite, http request would be 1.

Following sample code shows how we can use image sprite using HTML and CSS:

<html>
<body>
<div id="icons">
<div id ="twiiter"> </div>
</div>
<div id ="facebook"> </div>
</body>
</html>

#twiiter {
width: 79px;
height: 80px;
background: url("icons.png") 0 0;
}
// Height width define the portion of the image that we want to use
// background properties define the background image and its position (left 0px, top 0px)

It will display only twitter icon from this image.

If you need next facebook icons then we can use this CSS:

#facebook {
width: 80px;
height: 76px;
background: url("icons.png") -75px 0;
}

All images size can be different So we need to calculate background position according to the image size.

Output:

2

Leave a Reply

Your email address will not be published. Required fields are marked *