There are some solutions like SmartSprites ( link ), but I particularly do not like it because it generates a huge, hard-to-find CSS code.
A javascript solution with lean code and no library needed would look like this:
Fiddle: link
CSS
.sprite {
background: url("http://goo.gl/3pFUfC") -10000px -10000px transparent;
border: 1px solid #CCC;
}
JS:
for (var i = 0, imgs = document.getElementsByClassName('sprite'), len = imgs.length, size; i < len; i++) {
size = imgs[i].className.match(/(\d+)\-(\d+)/);
imgs[i].style.backgroundPosition = '-'+ (size[1]) +'px -'+ (size[2]) +'px';
}
HTML with multiple icons:
<img src="http://goo.gl/wAofVV"width="20" height="20" class="sprite 0-0" alt="" />
<img src="http://goo.gl/wAofVV"width="20" height="20" class="sprite 40-20" alt="" />
<img src="http://goo.gl/wAofVV"width="20" height="20" class="sprite 0-20" alt="" />
<img src="http://goo.gl/wAofVV"width="20" height="20" class="sprite 60-40" alt="" />
<img src="http://goo.gl/wAofVV"width="20" height="20" class="sprite 80-60" alt="" />
<img src="http://goo.gl/wAofVV"width="20" height="20" class="sprite 40-60" alt="" />
<img src="http://goo.gl/wAofVV"width="20" height="20" class="sprite 0-80" alt="" />
Some even wonder if it's worth the effort ( link ), but this way, it is easy to locate the images in the sprite, because I use round numbers. White spaces represent almost nothing in bytes. And no more javascript code is needed.
This was the most practical way I found it. But there are other very good ones as well.