Home > Sci/Tech > CSS Sprite Mistake

CSS Sprite Mistake

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. 🙂


My posts are not to serve as a replacement for recommendations provided by licensed physicians nor do they represent the opinions of Baylor College of Medicine or its affiliated institutions. Please read this site's Disclaimer and Terms of Use for more information.


Exit Pixel C – Enter iPad Pro

About a week ago, I sold my Pixel C and its keyboard for ~$500 on …


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