CSS: Sprites

By Xah Lee. Date: . Last updated: .

What is a CSS sprite?

here's explanation.

In many websites, it needs lots of icons.

Google Plus css sprites
Google Plus css sprites

Normally, each icon is a image file. For each image file, you need a HTTP request. Too many HTTP request makes your site loading slow. (regardless of the internet bandwidth, because each HTTP request usually means a TCP connection, and starting TCP connection has latency. 〔see TCP/IP Tutorial for Beginner〕)

(Note: another solution is using CSS: Data URI Scheme, but CSS sprites is in general more efficient, when your sprites are larger (say, bigger than 16×16 pixels, or you have more than 10 icons.).)

(Note: CSS sprite is often used by highly trafficked website that needs tens of icons. It also reduces server load. For small sites, you don't need it.)

CSS: Background Image

In order to do sprite, you need to understand the CSS background-image attribute.

Sprite Example

Google Plus css sprites
Google Plus css sprites

Here is a example of a (flame) icon using CSS sprite:

Code

<div class="flameicon"></div>
.flameicon {
 width: 17px;
 height: 22px;
 background-image: url("i/Google_Plus_css_sprites.png");
 background-position: -18px -20px;
}

How to find the “background-position” for a sprite icon?

The most important thing about sprites is positioning. Here's the steps of how to position a CSS sprite.

Suppose this is your image:

Google Plus css sprites
Google Plus css sprites

Suppose you want the red flame icon.

Find the coordinates of the upper-left corner. It is (18,20).

This is for the CSS offset background-position: -18px -20px.

Find the coordinates of the bottom-right corner. It is (35,42).

so the CSS is

.flameicon {
 width: 17px;
 height: 22px;
 background-image: url("i/Google_Plus_css_sprites.png");
 background-position: -18px -20px;
}

Sprites Gallery

Here is sample sprites used by popular sites. Many sites have more than one sprites image.

Twitter css sprites
Twitter css sprites
Google Plus sprites 11178 Google Plus sprites 88138
Google Plus
Facebook css sprites 2013
Facebook css sprites 2013
Facebook sprits 2013 RQB7y
Facebook sprits 2013 RQB7y
Google Plus css sprites Google Plus sprits 2
Google Plus sprites
Sina Weibo css sprites
Sina Weibo sprites

CSS, Background Image