Thursday, February 10, 2011

CSS Sprites: What They Are and How to Use Them ?

CSS Sprites :

A visually appealing website must have a great design. And usually with a great design, comes great images. And with great images, comes loading time. And with loading time, comes slow pages. ect, ect. Images are key in most web designs, so it’s always important to keep in mind how to optimize your images for the best user experience.
There are countless methods on minimizing the load time on your site, but this post will address one way in particular: sprites. More specifically, CSS sprites.


The use of CSS sprites is a fairly common practice with web designers. But what are they? The name may be a little misleading, as CSS sprites aren’t small, but big images containing dozens, and even hundreds, of little images. 
History :
Super Mario Bros. Sprites
Sprites originated in video games, back during the 8-bit glory days. Every visual item in a game was drawn as an individual image that would later be ‘layered‘ into the game as it was being played. However, as the complexity of games increased, game developers realized the benefits from combining all the images for a game into a singe sprite. By combining all the images into a single sprite (in a grid like formation), they could program the game to map positions of each individual graphic, and selectively placed them into the game.


What does this have to do with web development? Well, aren’t websites not unlike 8-bit games? Eh?
Why Sprites?
Sprite image from Google

Having all these images individually makes for smaller files sizes and fast loading, right? You may think so, but no. While it may look like your page loads fast, since there are dozens of images half loaded, they’re actually loading slower.


For each image, an HTTP-Request is called to download the image, and having a few dozen of them called at the same time slows down the entire process. Not to mention that despite a single image being smaller than a large sprite, file sizes add up, and fast. Combining a bunch of your images into a single sprite cuts down of your HTTP-requests, lowers the total file size, and your page then loads faster.

Example :

While the individual images on their own are smaller in size, collectively they’re more than 5x larger than the single sprite image.


Another great benefit to using sprites is when you use images for the :hover state. Normally, you’d have to use JavaScript to pre-load an image used in a :hover state, but if you’re using a sprite, and simply change the background position on :hover, there is no need to pre-load the image, since it will already be loaded. 



1 comments:

I am very much pleased with the topic you have chose for. I enjoyed every little bit part of it.
Melbourne Web Designer

Post a Comment

Share