For this blog post we will be covering basic image spriting using Compass along with Web Workbench from within Visual Studio. Using Sprites for multiple images in your websites reduces the amount of browser requests as well as reducing the total file size, creating faster loading web pages.
We will kick off by creating a new ASP.NET Website. We can then right click on the web site node in the Solution Explorer and select ‘Setup Compass Project’.
Once Compass is enabled you will see that two new folders have been created. One is called stylesheets which is where our scss is compiled, and the other is called [sass] where we will find our scss files.
For this example we will need to create three more things, an images folder with a sub-folder where we will place our sprites. It’s best to have all your sprites in one folder to make it easier to manage. For simplicities sake we also have a single HTML file that we’ll store — amazingly — our HTML in!
We need to include our outputted css, so include the screen.css file in the head of your HTML file. As well as the css, we need a button to style! I just used a simple link tag.
To sprite images together first you need images! I created 3 button states:
I’ve included the images in the btn sub-folder we made under images.
Once you have done this, right click on the btn folder and select ‘Generate Spriting Import’.
After generating the spriting import you’ll find that there is a new sprites folder in our sass folder. Inside will be our generated scss. We then include that file in our screen.scss file so the mixin’s defined in that file get included when we save our screen file.
Create your awesome button with scss, for the background images use the generated mixins created by compass, along with the image name.
We still need to change some defaults to make our button sprites work. Inside your config.rb file we have to uncomment “relative_assets”. We want our sprites to repeat horizontally we will need to change the default “no_repeat” to “repeat-x” on line 59 of our generated _btn.scss file. This is primarily for this tutorial, but it’s the easiest way to demonstrate this technique.
And that’s it! Our 3 small images are now sprited:
Feel free to Download the Source Files and have a look for yourself. :)
Don’t forget to grab the Web Workbench for Visual Studio here.