CSS sprites combine multiple images into a single image.

What is a CSS image sprite?

A webpage normally contains several images. These include icons, buttons, logos, relevant pictures and other graphics. Let’s say you have a blog and want to display four images. You have icons to indicate next page and a FAQ section, a share button and a teddy bear image. When an image is loaded onto the page, the browser makes an HTTP request to the server. Loading each image separately requires several HTTP server calls and can result in slow download times as well as high use of bandwidth.


Fig 1- Separate images

A way to reduce this unnecessary overhead is to use CSS image sprites. An image sprite takes all the smaller images and combines them into one large image. This reduces calls to the server, saves bandwidth and results in faster download times at the user end. Only the image you need is displayed on the desired page section while the rest of the images are essentially blacked out.


Fig 2- Image sprite

How to generate image sprites?

There are several ways to generate image sprites. One way is to write your own code in CSS using background-position. There are also a number of sprite generators available on the internet. Some popular ones are Spritepad, SpriteMe, and ImageMagick. If you are interested in more advanced features, the node package Sprity is available to be used in conjunction with NodeJS, Grunt and Gulp.

CSS Sprite Example

This code demonstrates how to implement an image sprite in CSS using background-position. Let’s use the images in Fig 1 above. We have an arrow, share button, teddy bear, and question mark that all need to be combined into one image. For simplicity we will assume that they are all the same size of 50 X 50 pixels. If the image sprite is positioned like in Fig 2 then the total size of the sprite is 100 X 100 pixels. The combined sprite needs to be named, here we’ll call it “mySprite.png”. Next we will set the images as background images in divs to create the sprite. In order to do this, we need to create div classes for each image. The div class for arrow will be named “.arrow” and the rest will follow this naming convention. In each class the width and height of the image are included. The image is called from ‘mySprite.png’ and is followed by the starting position of the image. The first one is positioned at (0px, 0px) which is the upper left-hand corner of the page.

Once these classes have been created, they can be called in your HTML code when you need the image. Below each div class is called to display the image. Note that the image sprite configuration in Fig 2 is not necessarily the best way to create the sprite. Sometimes it is better to lay out all the images vertically, horizontally or even diagonally. Sometimes it is best to create an image grid as shown above. The optimal configuration will depend on your application.