CSS sprites made easy with LessCSS

July 16, 2010

I’m working on a project now that involves building a Drupal theme from scratch from a designer’s PSDs. It’s something I don’t do often - the CSS I write is usually either in a modified stock theme or cut up by someone else. So I haven’t had much experience creating CSS sprites from scratch before.

Basically a sprite is a single image file containing other images that appear on the site. Each individual image (a button, logo, background, whatever) is then written in CSS with the sprite as the background image, a background-position, and a fixed width and height, so each slice of the big image appears where it’s needed. The main benefit is fewer HTTP requests, so the site loads faster. (With broadband it’s often not the loading itself that takes time but rather the requesting of each item.) It’s also easier to manage a few sprites than dozens of little files, and it’s just elegant.

The tools I’m using in this case are Photoshop and LessCSS. I know Photoshop decently well but am not an expert. LessCSS is a recent addition to my workflow, and it basically makes coding CSS a lot more efficient and intuitive with nesting, “mixins,” variables, calculations, and other little shortcuts. I use Less.app for Mac, so I just save my .less files in Textmate, and they get compiled (and minified) automatically.

I’m building the sprite with a simple photoshop grid of 60px horizontally and vertically. I align each picture with the top and/or left line of a grid square. So for each picture I just have to know: 1) the grid position (not pixel position), 2) pixel width and height.

In Less this works out like this:

@mastersprite-row: -60px;

#mastersprite {
  background-image: url('/path-to-theme/images/master-sprite.png');
  background-repeat: no-repeat;
  background-position: 0px 0px;
}

Then for the image at the 4th position down on the grid (the first being at 0px), I do:

#element {
  #mastersprite;
  background-position: 0 @mastersprite-row*3;
  width: [X]px;
  height: [Y]px;
}

And it just works. Beautiful.

Also part of this theming process but not related to sprites: the client had a font they wanted to use, in OpenType Font (.otf) format. I uploaded it to Font Squirrel’s Font-Face Generator and got a fully browser-compatible font package, including a CSS file which I simply @import‘d into my .less file and voila, the font worked.