Using sprites can significantly improve a webpage’s performance, we should definetly use them in all of our projects… But building sprites can be a pain.

This small Gulp task is meant to make it a lot easier to both build and use sprites. It does two things:

  1. Combine all the image contained in a folder into a unified sprite PNG file
  2. Generate CSS rules to easily include those images in a webpage.

The task:

gulp.task('sprite', function () {
    var spriteData = gulp.src('source_img/*.png') // Source images
            imgName: 'sprite.png', // Name of the final sprite
            imgPath: 'sprite.png', // Path to the final sprite
            cssName: 'sprite.css', // Name of the CSS file that will be generated
            cssTemplate: 'sprite.mustache' // Path to the mustache template (used to build the CSS file)

    var imgStream = spriteData.img
        .pipe(gulp.dest('.')); // Path to the final sprite

    return cssStream = spriteData.css
        .pipe(gulp.dest('.')); // Path to the generated CSS file

Example of generated sprite:


Example of CSS rules generated by the task:

.sprite {
    background: url("sprite.png") top left no-repeat;
    display: inline-block;
    vertical-align: middle;
    background-size: calc(512px/2) calc(384px/2);

.sprite-box {
    background-position: calc(-128px/2) calc(0px/2);
    width: calc(128px/2);
    height: calc(128px/2);
.sprite-browser {
    background-position: calc(-256px/2) calc(-128px/2);
    width: calc(128px/2);
    height: calc(128px/2);

Example of HTML using those classes to include images:

<div class="sprite sprite-box"></div>
<div class="sprite sprite-browser"></div>

This Gulp task has proven very useful to our team, it’s now included by default in all of our projects. If you’d like to grab the entire code or contribute to it, it’s available on my Github.