Sunday, November 15, 2009

Sass sprite mixin: making sprites super easy to use!

If you're like me, you love Haml and Sass!. And if you're a serious web developer trying to squeeze every last bit of performance out of your web application (let's pretend :), then you are already using image sprites, right?

I won't go into the benefits of using sprites, but apart from the obvious, I kinda like how they keep things organized. I don't need to worry about adding another small image to my application because it's not going to be yet another resource to bog things down, it goes in the sprite and probably only takes 1K. So that's nice. But they're just not as easy to use as a simple image...until now!

With my Sass mixin you can use a sprite image with just two lines of Sass.

The mixin:

// Add styles to an element to show the image in *image* at the given *x_pos* and *y_pos*.
// If the optional *x_size* or *y_size* arguments are passed in, the width and/or height 
// is set to that value.
=sprite(!image, !x_pos, !y_pos, !x_size=0, !y_size=0)
  :background-image = url(!image)
  :background-position = !x_pos !y_pos
  @if !x_size > 0
    :width = !x_size
  @if !y_size > 0
    :height = !y_size  
I'd recommend wrapping the mixin for your sprite image, because you're going to use it a lot. For example:
=player_sprite(!x_pos, !y_pos, !x_size=0, !y_size=0)
  +sprite("/images/player-sprite.png", !x_pos, !y_pos, !x_size, !y_size)
  
// Now define some styles using the player sprite
.playlists-icon
  +player_sprite(-600px, 0, 18px, 18px)
.recently-played-icon
  +player_sprite(-700px, 0, 18px, 18px)
.playing-now-icon
  +player_sprite(-800px, 0, 18px, 18px)
This will generate the following CSS
.playlists-icon {
  background-image: url('/images/player-sprite.png');
  background-position: -600px 0;
  width: 18px;
  height: 18px; }

.recently-played-icon {
  background-image: url('/images/player-sprite.png');
  background-position: -700px 0;
  width: 18px;
  height: 18px; }

.playing-now-icon {
  background-image: url('/images/player-sprite.png');
  background-position: -800px 0;
  width: 18px;
  height: 18px; }  
And your Haml to display the divs with the images is as simple as:
.playlists-icon
.recently-played-icon
.playing-now-icon
Awesome! Now that's easy!

If you found this useful, let me know!

2 comments:

Hernan said...

Thanks Karl, great post!

micHo said...

This is great, man. We're supercharging Teambox with sprites! :)