ScreenCast: Speed up image spriting with Compass

Follow us on LinkedIn for our latest data and tips!

Creating image icon sprites is a common development practice to save some file weight and reduce HTTP requests. But there’s one pitfall to using sprites: maintenance. Adding more icons to sprites or editing them is a real pain and takes valuable time away from writing code, especially when you have to recalculate the positions of the icons within your sprite and update your CSS accordingly.

Enter Compass. Compass is a CSS authoring framework that extends the functionality of the CSS preprocessor Sass. There are many things Compass can do, but that’s an article in itself. We’re going to solely focus on Compass’ sprite helpers.

According to the Compass docs, “(sprite helpers) make it easier to build and work with css sprites.” And they’re not joking; using Compass to help with sprite generation saves a TON of valuable time. And the best news of all? It only takes two short lines of code to generate a sprite from a folder full of images! Compare that to the time it takes in Photoshop to add or modify sprites.

How it’s done

Instead of creating a large Photoshop file with multiple layers of images or icons, you’ll instead need to save each icon individually to a unique folder (the folder name does not matter) as PNGs (Compass only supports PNGs at the moment).

Then in your SCSS file, after you’ve imported Compass (@import "compass";), simply declare which folder of images to import: @import "my-folder/*.png";. This will reference all files with a .png extension inside the folder my-folder.

Next, simply use a Compass include, which is what will actually spit out the sprite:

@include all-my-folder-sprites;

After running compass in the command line, you should now see a new image file in the directory above the original images’ folder (images, in our case), along with some CSS in your compiled stylesheet that will look similar to this:

.my-folder-facebook, // class names derive from the image file names
.my-folder-twitter {
  background: url('images/my-folder-s4fa3e9ddb3.png') no-repeat;

Finally, just declare the corresponding classes on your HTML element:

Now, whenever you want to add a new image to the sprite, or modify an existing one, just run compass!