Creating Sprite Files using Compass Gem

Objective

To learn how to generate sprite files using Compass gem and avoid creating them manually.

Steps

Step 1

Copy images to images/icons directory in the project we created in Hello SASS article.

Step 2

In sass/screen.scss file, add:

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

Step 3

Compile the scss file:

$ compass compile ./sass/screen.scss

This will create the sprite file, images/icons-s234c7f302b.png.

Step 4

The generated code for sprites in screen.css:

/* line 72, icons/*.png */
.icons-sprite, .icons-delete, .icons-edit, .icons-new, .icons-save {
  background-image: url('/images/icons-s234c7f302b.png');
  background-repeat: no-repeat;
}

/* line 84, ../../../../.rvm/gems/ruby-2.3.0@compass/gems/compass-core-1.0.3/stylesheets/compass/utilities/sprites/_base.scss */
.icons-delete {
  background-position: 0 0;
}

/* line 84, ../../../../.rvm/gems/ruby-2.3.0@compass/gems/compass-core-1.0.3/stylesheets/compass/utilities/sprites/_base.scss */
.icons-edit {
  background-position: 0 -32px;
}

/* line 84, ../../../../.rvm/gems/ruby-2.3.0@compass/gems/compass-core-1.0.3/stylesheets/compass/utilities/sprites/_base.scss */
.icons-new {
  background-position: 0 -64px;
}

/* line 84, ../../../../.rvm/gems/ruby-2.3.0@compass/gems/compass-core-1.0.3/stylesheets/compass/utilities/sprites/_base.scss */
.icons-save {
  background-position: 0 -96px;
}

You can download the source code for this article from rcompass.

Summary

In this article, you learned how easy it is to generate sprite files using Compass gem. This saves you time, since you avoid creating the sprite files manually. Using sprite files reduces the number of connections made to the server and improves the performance.

References

Tutorial to Compass and Sass
How to automatically generate CSS sprites with Sass and Compass


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.