Web Tips 1: I’ll Have a Sprite.

To get in the habit of blogging more, I'm going to share some tips I use to develop better performing websites. This might be a little technical for the average person but anyone who has dabbled in HTML and CSS recently should be able to follow along just fine. Today I am going to cover CSS sprites—a simple way to consolidate template images to reduce requests to the server. They are used by the biggest websites and I first learned about them 2 years ago by studying Facebook's HTML code with Firebug. I tend to take frequently used images such as the logo, icons, ribbons and shapes, and I lay them out in Photoshop in one image using a grid. My grid is usually made up of 5px squares with 25 or 50px divisions. I have a CSS class, usually titled .main_sprite, that contains my sprite as a background image and other classes for each image on the sprite such as .logo. My logo class would contain my normal rules, such as the width and height of the element and also the position of the logo image on the sprite. I simultaneously write the CSS code as I create the sprite so that I can lock down the co-ordinates. Here is an example:

.main_sprite{background-image:url('sprite.png');background-repeat:no-repeat;}
.logo{width:200px;height:100px;display:block;background-position:-100px -50px;}

In the HTML, I would create my logo like this:
<a href="index.php" class="main_sprite logo"></a>

That's all there is to it! You now have one large image that you might be using in place of 20 different images, but the server isn't opening and processing 20 different connections. You also have the benefit of more effective browser image caching as the image was loaded via CSS which leads to all around gains.

TAGS: ,

POSTED IN: Technology, Tips, Web

2 Responses to Web Tips 1: I’ll Have a Sprite.

  1. Mike May 3, 2012 at 2:35 pm

    That’s an interesting way to use Sprites that I had not thought of. The only way I have used sprites is (for websites) for buttons with rollover so it doesn’t have that split second load making it look from 1990. Or at least all images that are the same size and category (eg buttons), but from what I am gathering from your post, is that you would use it for all your major images.

  2. Andrew McCrea May 9, 2012 at 1:15 pm

    Definitely! Any image that helps complete the template is a good candidate for spriting. For example, even if your sprite file size is larger than the 20 individual files you consolidated to create it, you’ve reduced the major overhead of establishing 20 connections. You should still be mindful of laying out your sprite efficiently, but connections are the real killer.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>