Here it goes another post about new client-side stuff. Though, depends what you consider being 'new', sometimes I catch myself discovering new technology or tool, and thinking 'could it be that I was doing all of this manually rather than just letting code do the work for me?', and feel like dumbass. Can't really tell that same thing happened with Sass and Compass, since principally I'm not front-end developer, neither did I ever created sprites before. But faced with challenge of creating one, I remembered someone mentioned generating sprites via Compass, so was thinking giving it a try.
And there it was, magic in having all classes and background positions generated for you, rather than doing it by hand. Impressive!
Next on the list is Compass, CSS authoring tool (stated by Compass official page), from what I could tell, it's quite usefull for making your own grid system, creating sprites, has a collection of cross-browser compatible CSS3 mixins, and so on... Anyways, installing compass is not much different than installing Sass:
Once we have Sass and Compass installed, next thing is to create Compass project:
Now, you have to create directory where your images directory, and subdirectories for each sprite you wish to create (I've used arrow in this example). Once images grouped by directories, you need to tell compass where to search for your images files by modifying config.rb file in project root:
Config.rb file contents:
Now all left to do is to tell compass to create our sprite. Let's create file names arrows-sprite.scss and instruct Compass / Cass to create our sprite, and compile file into pure CSS:
/** arrows-sprite.scss file content **/
@import "arrows/*.png"; @include all-arrows-sprites;"
And here's where all the magic happened, we got our CSS file with classes matching image filenames, and png sprite. See contents of generated CSS, and sprite image below:
I guess you'll want to remove all of those ugly-looking comments that refer to Cass line of code that generated output. You do this by adding following line to config.rb :
line_comments = false
And you'll get clean-looking CSS as here.
You can checkout demo page on js bin below
If you wish to learn more about the ways you can make advantage of sprite-generating functions of sprite, check out official page.