Automate sprite creation with compass

Wouldn't it be great if we could throw inside of a folder, all our images and then they would be automatically combined together into one big sprite? But what about the CSS and the positions of each image sprite? What would happen if we added another image? Well, the best thing would be to magically understand the position of each one. Can this really be done? The answer is yes it can, with compass and scss and that's what I am going to write in this post.
First things first.
1) Add gem compass inside your gemfile and bundle it. For rails4 I am using it like this: 2) I am using SCSS and I have a main SCSS file where I am defining the rest of my SCSS files like this: 3) Add your images inside the folder assets/images/icons

4) Now it is time to define the necessary classes and the background images. I usually have a scss file, name variables where I am defining colors, font-families and all this kind of things. An example of it would be something like: As you can see in the sprites section, I am defining the icons folder (you can name it whatever you want) and a basic sprite class with spacing 30px. This means that each image will be combined with a distance of 30px from the other images, inside the big sprite. I usually do it like this so I don't have any image close to another and prevent it from appearing when I am displaying through CSS. Then I am defining another class with the background-position and the dimensions of each specific sprite. You can find more of these useful options and much more in the official compass reference. As you can see, the background-position and the image dimensions will be automatically set without doing anything extra. Everytime we add another image inside the folder, it will do the same and we don't need to worry about these details, we just have to define it inside our scss like this!

5) If you visit a page with the above scss it will create my sprite. It will look like this icons-s93d4b80bca.png inside your assets/images folder. If you open it you will see all the png images combined from the folder icons of the assets/images/icons. It will create your CSS, you can call and show the sprite as you would do if you had the above CSS classes. Of course you can remove the .background-sprite class and just add the background inside all of your sprite css classes, it's up to you.

Troubleshooting and tips

If you want to regenerate your icons file, just remove the icons-whatever.png. Then do a minor change to the scss file with the mapping (like changing the line-spacing) and visit a page in which you have defined the specific scss. It will generate it again for you. For more information about assets pipeline, read my other post.
comments powered by Disqus