Last Updated: February 25, 2016
·
2.564K
· alettieri

Sprites using Compass

Have a ton of images? Let compass sprite them for you.

Use compass' sprite helper: http://compass-style.org/reference/compass/helpers/sprites/

Example

Say we have a few .png images in an icon folder: images/icons/

We can have compass sprite those images into one image, then use the image names to determine their x/y positions.

In the below example, we'll specify classes for a couple of images in the icon folder. Say, comment.png and info.png.

// Create the sprite map object.
$icons = sprite-map( "images/icons/*.png" );

.icon {
    background: {
        image: $icons;
        repeat: no-repeat;
        color: transparent;
        position: 0 0;
    };
    // Comment icon
    &.comment {
        background-position: sprite-position( $icons, comment );
    }
    // Info icon
    &.info {
        background-position: sprite-position( $icons, info );
    }
}

The churned out css is something like:

.icon {
    background-image: url( 'images/icons-84958922.png' );
    background-repeat: no-repeat;
    background-color: transparent;
    background-position: 0 0;
}

.icon.comment {
    background-position: 0px 0px;
}

.icon.info {
    background-position: 40px 0px;
}

I came up with fictitious values for the positions. Hopefully you get the point.

You can also offset the positions by passing in additional parameters:

.icon {
    ....
    .comment{
        background-position: sprite-map( $icons, comment, 2px, 0 );
    }
}

Turns out:

.icon.comment{
    background-position: 42px 0px;
}