Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Juice10/2700716 to your computer and use it in GitHub Desktop.
Save Juice10/2700716 to your computer and use it in GitHub Desktop.
Using Compass to generate normal and retina sprite maps
@mixin sprite-background($name, $folder, $sprite-width) {
$sprites: sprite-map("#{$folder}/*.png");
$sprites-retina: sprite-map("#{$folder}@2x/*.png");
background-image: sprite-url($sprites);
background-position: sprite-position($sprites, $name);
background-repeat: no-repeat;
display: inline-block;
height: image-height(sprite-file($sprites, $name));
width: image-width(sprite-file($sprites, $name));
@media (-webkit-min-device-pixel-ratio: 2), (-o-min-device-pixel-ratio: 3/2), (min-device-pixel-ratio: 2) {
$ypos: round(nth(sprite-position($sprites-retina, $name), 2) / 2);
background-position: 0 $ypos;
// There must be a way of detecting this width.
@include background-size($sprite-width auto);
background-image: sprite-url($sprites-retina);
}
}
@chrisyour
Copy link

Great mixin. You can replace the inline-block line with the @include inline-block mixin to be cross-browser friendly as well as make use of the image-width method to remove the need for the $sprite-width param.

@mixin sprite-background($name, $folder) {
  $sprites: sprite-map("#{$folder}/*.png");
  $sprites-retina: sprite-map("#{$folder}@2x/*.png");

  background-image: sprite-url($sprites);
  background-position: sprite-position($sprites, $name);
  background-repeat: no-repeat;
  @include inline-block;
  height: image-height(sprite-file($sprites, $name));
  width: image-width(sprite-file($sprites, $name));
  @media (-webkit-min-device-pixel-ratio: 2), (-o-min-device-pixel-ratio: 3/2), (min-device-pixel-ratio: 2) {
    $ypos: round(nth(sprite-position($sprites-retina, $name), 2) / 2);
    background-position: 0 $ypos;
    background-size: image-width(sprite-file($sprites, $name)) auto;
    background-image: sprite-url($sprites-retina);
  }
}

@mohsen1
Copy link

mohsen1 commented Jun 14, 2013

Why min-device-ration should be 2? If a device supports min-device-ratio it supports background-size so it can scale down the 2x image. I think we can use 2x images for pixel ratios less than 2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment