CSS Sprite Images benefits

In almost all the web application, we use many icons to make our pages look elegant. This might be good for the UI/UX but it has a huge implication on the network performance.
Consider a page which shows 45 various services provided by an organisation. There will be 45 network calls required to get all the icons. Each browser opens a certain maximum number of connections in parallel to optimize its performance (Chrome opens max 6 connections at a time).
One way of getting all the images at once is to use domain sharding, in our case we need 45/6 = 8 (rounded off) different domains to serve all the icons at once.

Another and the popular way of achieving it is by using Sprite Images. Its a single image which contain all the icons in it. CSS can be used to display all the icons at their respective places in the web page.
The following link has 33 icons which are served through a single Sprite image.

Max hospital

This is the sprite image used

Sprite image

How to create and use Sprites:

There are a lot of CLI/GUI tools to generate the sprite image. The above image has been used using Python based CLI tool called Glue.

Glue Website

Just pass the directory of icons and it will generate a PNG image with all the icons and a CSS file with all the image names as classes. Use these classes in HTML where ever you want to show the icons. The sprite image and CSS file can be customized in several ways as required by the developers. Please refer its documentation for all possible options.

Example usage of the tool :

glue-sprite icons/ –img=assets/images/ –css=. –sprite-namespace= –namespace= –force

Explanation of the command:

icons/ – directory with all the icons

–img = assets/images/ – the sprite image will be created under this path (this path is used so that generated CSS classes also get the assets/images path – standard path for serving images through rails).

–css = . CSS file will be created in the current directory.

–sprite-namespace = to append anything in class name

–namespace= to prepend anything in class name

–force – not to cache while creating sprite.

A sample of CSS file generated:

.wi_fi_zone{background-position:-243px -30px;width:28px;height:23px;}
.blood_bank{background-position:-243px -53px;width:18px;height:28px;}
.default_service{background-position:-243px -81px;width:21px;height:23px;}
.default_specialty{background-position:-243px -104px;width:21px;height:23px;}
.mobile{background-position:-243px -127px;width:22px;height:22px;}
.email{background-position:-243px -149px;width:16px;height:14px;}