Sprites with Compass
Usingis 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, , or .
If you do want to use them, this is fortunately made very easy if you use.
Let's assume you have two images
.../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
:assetsgroup in your Gemfile:
config/compass.rbwith the following content:Copy
project_type = :rails generated_images_dir = 'app/assets/images/sprites'
Restart your server.
Move the two images into a new folder
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.
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("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
width of the original image, by using
Finally, you can add additional offsets by using
+buttons-sprite("blue-button", false, x-offset, y-offset)
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:
Compass gives you a lot more, as well as a .