Skip to content

Instantly share code, notes, and snippets.

@wanderingmatt
Created October 1, 2012 17:19
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save wanderingmatt/3813139 to your computer and use it in GitHub Desktop.
Save wanderingmatt/3813139 to your computer and use it in GitHub Desktop.
Mixin that generates both a regular and retina sprite (using the Compass Sprite Helpers) and returns the appropriate declarations and media queries.
// Mixin that generates both a regular and retina sprite (using the Compass Sprite Helpers) and returns the appropriate declarations and media queries.
//
// $folder - The name of the folder that contains the icons to sprite.
//
// No styleguide reference.
@mixin retina-sprite($folder) {
$sprites: sprite-map("icons/#{$folder}/*.png"); // Generates a sprite containing every icon in the supplied folder.
$sprites-2x: sprite-map("icons/#{$folder}@2x/*.png"); // Generates a second sprite containing every icon @2x resolution.
background-image: sprite-url($sprites);
background-repeat: no-repeat;
@include inline-block;
text-indent: -9999px;
@each $sprite in sprite-names($sprites) {
&.#{$sprite} {
background-position: sprite-position($sprites, $sprite);
height: image-height(sprite-file($sprites, $sprite));
width: image-width(sprite-file($sprites, $sprite));
}
}
@media (min-resolution: 2dppx), (min-device-pixel-ratio: 2), (-o-min-device-pixel-ratio: 2/1), (-webkit-min-device-pixel-ratio: 2) {
background-image: sprite-url($sprites-2x);
@include background-size(100% auto);
@each $sprite in sprite-names($sprites-2x) {
&.#{$sprite} { background-position: nth(sprite-position($sprites-2x, $sprite), 1) nth(sprite-position($sprites-2x, $sprite), 2) / 2; }
}
}
}
@thenikso
Copy link

thenikso commented Jul 3, 2013

Thank you for this, I'm using a slightly modified version to have classes like the one generated by Compass' @include all-<sprite>-sprites:

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

  @each $sprite in sprite-names($sprites) {
    .#{$folder}-#{$sprite} {
        background-image: sprite-url($sprites);
      background-position: sprite-position($sprites, $sprite);
      height: image-height(sprite-file($sprites, $sprite));
      width: image-width(sprite-file($sprites, $sprite));
    }
  }
  @media (min-resolution: 2dppx), (min-device-pixel-ratio: 2), (-o-min-device-pixel-ratio: 2/1), (-webkit-min-device-pixel-ratio: 2) {
    @each $sprite in sprite-names($sprites-2x) {
      .#{$folder}-#{$sprite} {
        background-image: sprite-url($sprites-2x);
        background-position: nth(sprite-position($sprites-2x, $sprite), 1) nth(sprite-position($sprites-2x, $sprite), 2) / 2;
        @include background-size(100% auto);
      }
    }
  }
}

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