Skip to content

Instantly share code, notes, and snippets.

@fourseven
Created August 16, 2012 09:19
Show Gist options
  • Save fourseven/3368685 to your computer and use it in GitHub Desktop.
Save fourseven/3368685 to your computer and use it in GitHub Desktop.
A compass function to handle spriting with normal and retina images automatically.
// @Mixin Retina Sprite Sass
// ======================================================
// This requires two folders full of *.png files, normal and then
// 2x resolution. Please ensure that they have the same number and names
// of files.
// I've written this based off other efforts on the web, but none did
// both background-images and a set of sprites automatically.
// Still very much a work in progress.
// To use see the bottom three lines.
// Build off the standard compass sprite utils.
@import "compass/utilities/sprites/base";
// per sprite background image and dimentions.
// @private
@mixin retina-sprite($name, $sprites, $dimensions: true, $pad: 0) {
background-position: sprite-position($sprites, $name, -$pad, -$pad);
@if ($dimensions == true) {
@include sprite-dimensions($sprites, $name);
}
@if ($pad > 0) {
padding: $pad
}
}
// Base sprite files and media query.
// @private
@mixin retina-sprite-class($className, $map, $map2x) {
// the other option here is as follows:
//[class^="#{$className}-"]
// (which does #{spritename}- matching on classes, but didn't work in my case as I have #{spritename} classes)
[class*="#{$className}"] {
background-image: $map;
background-repeat: no-repeat;
@media (-webkit-min-device-pixel-ratio: 2), (min--moz-device-pixel-ratio: 1.5), (-o-min-device-pixel-ratio: 3/2), (min-device-pixel-ratio: 2) {
background-image: $map2x;
@include background-size(ceil(image-width(sprite-path($map2x)) / 2) auto);
}
}
}
// This is the public function, feed it two maps of sprites, the normal and then the retina maps.
@mixin retina-sprites($map, $map2x, $names: sprite-names($map)) {
@each $sprite in $names {
.#{sprite-map-name($map)-$sprite} {
@include retina-sprite($sprite, $map, true);
}
}
@include retina-sprite-class(sprite-map-name($map), $map, $map2x);
}
// Here's where I'm using it, the icn folder has my normal sprites, and
// icn-retina is self explainatory. The following three lines are all needed.
// Please adjust to suit your project.
$map: sprite-map("icn/*.png");
$map2x: sprite-map("icn-retina/*.png");
@include retina-sprites($map, $map2x);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment