I extended it a little bit to enable custom width and height settings. This might come in handy if you for example want to change the size of your image for smaller screens.
Define your image and size like so:
@include use-sprite(my-image, 120px, 42px);
Note that if you don't set size, the image will be sized as per default.
Please also note that this hasn't be tested thoroughly.
//Sprite mixin, works perfectly with standard defines
@mixin use-sprite($sprite, $width:null, $height:null) {
background-image: sprite-url($icons);
background-repeat: no-repeat;
overflow: hidden;
display: block;
@if($width != null and $height != null) {
// If width and height has been defined, calculate ratio
$ratio: image-width(sprite-file($icons, $sprite)) / $width;
background-size: (round(image-width(sprite-path($icons)) / $ratio)) round((image-height(sprite-path($icons)) / $ratio));
background-position: round(nth(sprite-position($icons, $sprite), 1) / $ratio) round(nth(sprite-position($icons, $sprite), 2) / $ratio);
width: $width;
height: $height;
} @else {
// If it hasnt been set, use default
background-position: sprite-position($icons, $sprite);
width: image-width(sprite-file($icons, $sprite));
height: image-height(sprite-file($icons, $sprite));
}
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 2dppx) {
background-image: sprite-url($icons-2x);
@if($width != null and $height != null) {
// If width and height has been defined, calculate ratio
$ratio: image-width(sprite-file($icons-2x, $sprite)) / $width;
background-size: (round(image-width(sprite-path($icons-2x)) / $ratio)) (round(image-height(sprite-path($icons-2x)) / $ratio));
background-position: round(nth(sprite-position($icons-2x, $sprite), 1) / $ratio) round(nth(sprite-position($icons-2x, $sprite), 2) / $ratio);
width: $width;
height: $height;
} @else {
// If it hasnt been set, use default 2x
background-size: (image-width(sprite-path($icons-2x)) / 2) (image-height(sprite-path($icons-2x)) / 2);
background-position: round(nth(sprite-position($icons-2x, $sprite), 1) / 2) round(nth(sprite-position($icons-2x, $sprite), 2) / 2);
width: image-width(sprite-file($icons-2x, $sprite)) / 2;
height: image-height(sprite-file($icons-2x, $sprite)) / 2;
}
}
}
Great idea. I would like to make it scale automatically when you only provide a width or height though. For cases like this isn't using SVG a better solution?
Thanks for a great mixin!
I extended it a little bit to enable custom width and height settings. This might come in handy if you for example want to change the size of your image for smaller screens.
Define your image and size like so:
Note that if you don't set size, the image will be sized as per default.
Please also note that this hasn't be tested thoroughly.