CSS Sprite Mistake

0

From time to time, people will ask me to validate and/or optimize their web code to streamline performance. People are now getting comfortable with using CSS sprites on their sites, but unfortunately I’ve seen this very easy-to-fix problem twice, and thought I should let people know how to resolve it.

When you’re writing the “rules” for the sprite in your stylesheet, there’s no need to include a path to the sprite image with every class. In other words, the example below will still work, but I don’t think it’s the best route to take.

.page { background: url(https://your.domain/images/test.jpg) 0 -792px;}
.printer { background: url(https://your.domain/images/test.jpg) 0 -858px;}
.sitemap { background: url(https://your.domain/images/test.jpg) 0 -924px;}

Instead, define two classes – one which points to the sprite image and another which defines its fixed position on that image.

.sprite {background-image: url(https://your.domain/images/test.jpg)}
.page {background-position: 0 -792px;}
.printer {background-position: 0 -858px;}
.sitemap {background-position: 0 -924px;}

Now when you wish to utilize the sprite image in your HTML/PHP elements, you need to include both the “sprite” class (in the example above) and the location class (page, printer, or sitemap) as in the following example.

<span class=”sprite sitemap”>Website Sitemap</span>

This technique could really lighten your stylesheet if you have lots of sprite image references to make. 🙂

 LEAVE A REPLY

Please enter your comment!
Please enter your name here