Working with Sprite Sheet using CSS

What is a Sprite image?
Let us first understand what we mean by Sprite image. Sprite image is a single image which contains multiple images inside it i.e. multiple images saved inside a single image with specifically defined X and Y coordinates. For example, check the below image which contains many images inside it:


Why use a Sprite image?
Since for such a long time we have been loading a single images while doing web development, then why do we need to use Sprite images and make our code complicated?

A simple answer is to reduce to load time of website. Our website can contain many small and large images. Small images can be icons, logos, buttons, etc. and in case you are developing a web game these small graphic elements can be in 100’s. So to load all these images separately we need to make multiple server request which will result in increased loading time.

If we put all these small images in a single image file, then rather than making multiple server requests we need to make a single request which will decrease the load time of the website and will make it more responsive. After loading of the image we can display a part of that image at a time.

Also the size of the single sprite image will be less than the combined size of the individual images.

How to create a Sprite sheet?
You can generate a sprite sheet using couple of methods. First you can use many free website available which provide the free facility to generate sprite sheet. Some of the web URL’s are mentioned below.

or else you can use Node, Grunt or Gulp to generate your sprite sheet. More about how to create sprite sheets using node, gulp, grunt, etc can be found here.

How to use a Sprite sheet?
Since all the images are in a single file, what we can do it set the ‘background’ property of all the CSS classes who will use this image.

.block-1, .block-2, block-3{
background:url("sprite.png") no-repeat;

Next for each individual class we can specify which portion of the image has to be used i.e. x-position, y-position, width and height.

.block-1, .block-2, block-3{
background:url("sprite.png") no-repeat;

background-position:5px 15px;

Related Posts