Posted about 6 years ago. Visible to the public.

Sprites with Compass

Using CSS sprites for background images is a technique for optimizing page load time by combining smaller images into a larger image sprite.

There are ongoing arguments on how useful this still is, as modern browsers become more comfortable to load images in parallel. However, many major websites still use them, for example amazon, facebook, or twitter.

If you do want to use them, this is fortunately made very easy if you use compass.

Simple example for Rails 3+

Let's assume you have two images app/assets/images/layout/blue-button.png, and .../blue-button-hover.png and the following sass:

Copy
.blue-button ... background: image-url("layout/blue-button.png") no-repeat &:hover background: image-url("layout/blue-button-hover.png") no-repeat

You can turn them into a sprite using the following steps:

  1. If not there already, add this to the :assets group in your Gemfile:
    gem 'compass-rails'
    gem 'oily_png'
  2. Run bundle install.
  3. Add a config/compass.rb with the following content:

    Copy
    project_type = :rails generated_images_dir = 'app/assets/images/sprites'
  4. Add app/assets/images/sprites to your .gitignore.
  5. Restart your server.
  6. Move the two images into a new folder app/assets/images/layout/buttons.
  7. Change your sass stylesheet to:

    Copy
    @import "compass/utilities/sprites/base" @import "layout/buttons/*.png" .blue-button +buttons-sprite("blue-button") &:hover +buttons-sprite("blue-button-hover")

That should be it.

How it works

If you do @import "buttons/*.png" (where buttons is only an example), compass will generate the big sprite and give you a new mixin called +buttons-sprite.

+buttons-sprite("blue-button") will expand into
background: url(path-to-icon-sprite) no-repeat 0 offset-to-cross-icon

You can also have compass include the height and width of the original image, by using
+buttons-sprite("blue-button", true)

Finally, you can add additional offsets by using
+buttons-sprite("blue-button", false, x-offset, y-offset)

Spacing

When your HTML element is larger than the image you're using, other images in the same sprite can bleed into it. To get around this, you can add some transparent spacing around an image, by setting a sass variable that matches your image name like this:
$buttons-blue-button-spacing: 20px
@import "buttons/*.png"

More info

Compass gives you a lot more mixins, customization options as well as a detailed tutorial.

Does your version of Ruby on Rails still receive security updates?
Rails LTS provides security patches for old versions of Ruby on Rails (3.2 and 2.3).

Owner of this card:

Avatar
Tobias Kraze
Last edit:
about 4 years ago
by Andreas Herz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Tobias Kraze to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more