Generate Sprites with Compass

A major benefit using Sass frameworks is the ability to combine multiple images into a single sprite. Here is how to generate sprites with Compass.

If you’ve set up a Compass project, within it, open up the config.rb file and you should see some paths defined.

// config.rb

# Set this to the root of your project when deployed:
http_path = "/"
css_dir = "stylesheets"
sass_dir = "sass"
images_dir = "images"
javascripts_dir = "javascripts"

Change the http_path to your project location and you’ll be ready to start generating sprites.

Also defined in the config.rb file is the image directory location, images_dir. This can be left as "images" for now.

If an images directory doesn’t exist within your Compass project, create one now and within this directory, create an icons folder.

Within this icons folder, copy the images you would like to use to generate the sprite.

It is worth noting that Compass only supports .png files, so ensure that you just use these image types.

Within the screen.scss file, add the following lines just underneath the @import "compass/reset"; line.

// sass/screen.scss

@import "compass/utilities/sprites";
@import "icons/*.png";
@include all-icons-sprites;

The icons/*.png suggests that all of the images within the icons directory that have the .png extension will be used to generate the sprite.

The @import "compass/utilities/sprites"; line tells Compass to generate a stylesheet that is customised for your sprites.

Assuming you are running the compass watch command whilst adding the above lines, you should notice that a sprite file has been generated within your project’s images directory.

The sprite generated should be named similar to icons-s5ba927bd9b.png with the icons- prefix originating from the name of the directory inside the images folder (icons).

Within the screen.css file, some CSS styles have been automatically generated to allow you to access the images within the sprite file.

For example, an image1.png and image2.png might generate the following CSS.

// stylesheets/screen.css

/* line 56, icons/*.png */
.icons-sprite, .icons-image1, .icons-image2 {
  background-image: url('/path/to/compass-project/images/icons-s5ba927bd9b.png');
  background-repeat: no-repeat;
}

/* line 84, ../../../../../../Library/Ruby/Gems/2.0.0/gems/compass-core-1.0.3/stylesheets/compass/utilities/sprites/_base.scss */
.icons-image1 {
  background-position: 0 0;
}

/* line 84, ../../../../../../Library/Ruby/Gems/2.0.0/gems/compass-core-1.0.3/stylesheets/compass/utilities/sprites/_base.scss */
.icons-image2 {
  background-position: 0 -434px;
}

Now the .icons-image1 and .icons-image2 rules can be used to display the individual images from within your web project.