Sprite

Arguments

NameTypeDescription
$image-urlstring

The URL link of the sprite image. Important: Don’t forget that the image link must be either absolute or relative to the generated CSS file.

$positionnumber | string

Sets the positioning of the background-image. Multiple values must be seperated by space.

* To learn more about the background-position property values check out the links at the end of the page.

Examples

You can apply it to one single element and pass both $image-url and $position arguments by using one-line method.

Important: Don’t forget to give a width and height values to the selected element. It is very important to know the exact size of an image that you want to select from a sprite sheet.
.sprite-element{
  @include sprite("../images/sprite.png", 0 0);
}
//CSS Output
.sprite-element {
  display: inline-block;
  background-image: url("../images/sprite.png");
  background-position: 0 0;
  background-repeat: no-repeat;
}

Or you can apply it to multiple elements with different images selected from a single sprite sheet. Well, suppose you have a markup like the one below, and you want to assign different background images to each element from a single sprite sheet.

<div class="sprite-element first"></div>
<div class="sprite-element second"></div>
<div class="sprite-element third"></div>
<div class="sprite-element fourth"></div>

First let’s call the mixin just to define the sprite image’s url link and specify the width and height of the image that we’re going to select.

.sprite-element{
  width: 100px;
  height: 100px;
  @include sprite("sprite.png");
}

You can pass width and height values into the mixin as well!

.sprite-element{
  @include sprite("sprite.png") {
    width: 100px;
    height: 100px;
  };
}

Then let’s pass the positioning values for each of the elements separately using the secondary classes on them.

.sprite-element{
  @include sprite("sprite.png") {
    width: 100px;
    height: 100px;
  };
  &.first {
    @include sprite(0 0);
  }
  &.second {
    @include sprite(-100px 0)
  }
  &.third {
    @include sprite(-200px 0)
  }
  &.fourth {
    @include sprite(-300px 0)
  }
}

Well, the result will be like this:

//CSS Output
.sprite-element {
  width: 100px;
  height: 100px;
  display: inline-block;
  background-image: url("sprite.png");
  background-repeat: no-repeat;
}
.sprite-element.first {
  background-position: 0 0;
}
.sprite-element.second {
  background-position: -100px 0;
}
.sprite-element.third {
  background-position: -200px 0;
}
.sprite-element.fourth {
  background-position: -300px 0;
}

Easy, isn’t it?