Tag Archives: optimizations

CSS Sprites – common mistakes

CSS Sprites

Although there are so many resources about CSS sprites and where they should be used I still think their usage is misunderstood.

The big problem is that many people use the sprite in a completely wrong way. When used properly the sprite can be really helpful, especially for a large scale site.

The mistake

When you read about sprites and you understand you must use only one image you start doing the big mistake. Let’s assume we’ve one image for the backgrounds of three div elements:

.a {
    background: url(sprite.png) 10px 10px no-repeat;
}
.b {
    background: url(sprite.png) 20px 20px no-repeat;
}
.c {
    background: url(sprite.png) 30px 30px no-repeat;
}
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>

Now even with this simple example there is one sprite image but the browser makes three requests for this image, which is really bad!

The solution

How about making it the right way with a simple change:

.sprite {
    background-image:url(sprite.png);
    background-repeat: no-repeat;
}
.a {
    background-position:0px 0px;
}
.b {
    background-position:10px 10px;
}
.c {
    background-position:20px 20px;
}

and a little bit different markup:

<div class="sprite a"></div>
<div class="sprite b"></div>
<div class="sprite c"></div>

and this is where the sprites are really useful. Now the browser makes only one request and your site is ready for the big world.