Using CSS sprites for background images Show archive.org snapshot 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 Show archive.org snapshot , facebook Show archive.org snapshot , or twitter Show archive.org snapshot .
If you do want to use them, this is fortunately made very easy if you use compass Show archive.org snapshot .
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:
.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:
-
If not there already, add this to the
:assets
group in your Gemfile:
gem 'compass-rails'
gem 'oily_png' -
Run
bundle install
. -
Add a
config/compass.rb
with the following content:project_type = :rails generated_images_dir = 'app/assets/images/sprites'
-
Add
app/assets/images/sprites
to your.gitignore
. -
Restart your server.
-
Move the two images into a new folder
app/assets/images/layout/buttons
. -
Change your sass stylesheet to:
@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 Show archive.org snapshot , customization options Show archive.org snapshot as well as a detailed tutorial Show archive.org snapshot .