CSS Sprite Mistake

Published: 1 year, 8 months ago (Jun 6, 2010) in Sci/Tech
Tags: ·  Print This Post ·  Leave a Comment

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(http://your.domain/images/test.jpg) 0 -792px;}
.printer { background: url(http://your.domain/images/test.jpg) 0 -858px;}
.sitemap { background: url(http://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(http://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. :-)

Legal

As a third year medical student at Baylor College of Medicine, my posts are intended to educate others and share my experiences from this incredible journey without violating patient privacy at all costs. These blurbs are not to serve as a replacement for recommendations provided by licensed physicians under any circumstance.

Share This Post

Speak Your Mind...

XHTML: You can use these tags: <a href=""> <i> <b> <code>

Gravatar: Want to personalize your comments with a picture? Get a free Gravatar!