Thursday, November 27, 2014

css spritesheets

CSS spritesheets, putting a bunch of images in one big image (so that http round trips are minimized) and then using CSS to just show the correct image subset of the full sheet, is a good trick to know about. (I suddenly started wondering if advances in the http protocol would make them less crucial, and allow multiple files to be downloaded in one gulp, so to speak.. googling to check that out brought me to a page saying you should embed images as encoded text in the CSS which seems to be taking it a bit too far!)

Anyway, I found it convenient to use good ol' ImageMagick. This page goes into some detail, but the net-net was doing:
convert img1.png img2.png img3.png -append spritesheet.png
was all I needed. That gave me a single .png with all the images in a vertical stack. I then made a quick perl script to generate the css, something like
.img {
    background-image: url('spritesheet.png');
       background-position: 0px 0px
       background-position: 0px -50px

(I had 25 of these to do). The important thing here is the offset, which is increasingly negative for each subsequent image.

The HTML was then something like
<div class="img thing1"></div>
<div class="img thing2"></div>
This raises best practices / style questions. W3Schools recommends using the img tag with a placeholder for the src (lest your html be invalid), ala:
<img class="thing1" src="img_trans.gif">
I see that it's kind of cool to keep things an image (even better would be list item tags or other semantically meaningful html tags) but going back to the old "transparent GIF" placeholder thing gives me the creeps!

Also you can run your generated file through an online image compressor... and there are even other online tools to smush the image together and give you the resulting CSS.

No comments:

Post a Comment