SPRITE in automated css

Asked

Viewed 89 times

0

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

For example, taking html below:

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

Or some similar variation, such as displaying the tag as an image, without creating a huge or giant code ?

1 answer

1

There are some solutions like Smartsprites (http://csssprites.org), but I particularly don’t like it because it generates a huge and difficult to locate CSS code.

A javascript solution, with streamlined code and no library required, would look like this:

Fiddle: http://jsfiddle.net/ZT5Uk/

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 (https://webmasters.stackexchange.com/questions/32976/css-sprites-are-they-worth-the-trouble/32982#32982), 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 required.

This was the most practical way I found. But there are other very good ones too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.