Get rid of many page requests; use CSS sprites

Aug9
  • Share

Difficulty: ★☆☆☆☆
This trick is so easy but unfortunately not much used on the web.
There are 2 pro-reason, why you should start using sprites (a technique which is used a lot for 2D game-developing / making one big image file, containing all the site images) in CSS.

  1. Get rid of the image flickering. This is what happens when using roll-overs for multiple images, both images will be requested from the server. Although the time is pretty fast, you’ll will see the image flickering
  2. Reduce page requests – One big image might be heavier to download, nowadays it will be faster and directly loaded in your page then requesting multiple images

There are some handy Firefox tools, which you can use for website performance optimization:
Live HTTP Headers and Firebug.
Within Firebug, you can select the NET tab. From here you can see all the requests to images.

See the sprites which are used for Amazon, YouTube or even for Google.

There are even online tools for generating these sprites, so you don’t need Photoshop for calculating.

How to implement it? – Just by smart using the background property.
For example:

#navigation {
 width: 500px;
 height: 20px;
 overflow: hidden; //no image outside the defined clipping area is visible
}

#navigation a {
 display: block;
 width: 100px;
 height: 20px;
 text-indent: -10000px; //for removing the link text off the screen
 background-image: url(sprite.png) //link to your sprite image;
}

#nav-home a { background-position: 0 0; //position of sprite x y }
#nav-home a:hover { background-position: 0 100px; //note the changed y-position }
#nav-about a { background-position: 20px 0; }
#nav-about a:hover { background-position: 20px 100px;}

You can put everything in your sprite, think about icons, backgrounds, borders and corners.
It’s even possible to combine it with background repeating.



Leave a comment