SPRITE in automated css

0

The use of CSS Sprites has become very popular, for performance reasons in particular. How to implement sprite using automated and elegant code?

For example, having the html below:

<span class="sprite home" >&nbsp;</span>

> css or giant code ?

    
asked by anonymous 20.03.2014 / 16:17

1 answer

1

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.

    
20.03.2014 / 16:17