Skip to content

Instantly share code, notes, and snippets.

@brewster1134
Last active August 29, 2015 14:00
Show Gist options
  • Save brewster1134/13162e2cb0220e87b017 to your computer and use it in GitHub Desktop.
Save brewster1134/13162e2cb0220e87b017 to your computer and use it in GitHub Desktop.
Compass Spriting w/ Retina & Media Query Support
// INIT
// call the all-sprites mixin to generate the base styles
+all-sprites
// with MARKUP
// the following markup with generate retina assets for retina display, or regular images if a regular display
// <div class="global-image1"/>
// with SASS
// if you need to share a sprite with another element, just extend it
.foo
@extend .global-image1
// with MEDIA QUERIES
// if you need to use sprites inside of @media, use the get-sprite mixin
@media (min-width: 600)
.foo
+get-sprite(image1)
=for-retina
@media (-webkit-min-device-pixel-ratio: 2), (-o-min-device-pixel-ratio: 3/2), (min--moz-device-pixel-ratio: 2), (min-device-pixel-ratio: 2), (min-resolution: 144dppx)
@content
$global-sprites: sprite-map("global/**/*.png", $layout: smart)
$global-retina-sprites: sprite-map("global-retina/**/*.png", $layout: smart)
=all-sprites
$base-class: sprite-map-name($global-sprites)
.#{$base-class}-sprites
background-image: sprite-url($global-sprites)
background-repeat: no-repeat
$sprite-names: sprite-names($global-sprites)
@each $sprite in $sprite-names
.#{$base-class}-#{$sprite}
@extend .#{$base-class}-sprites
+get-sprite($sprite)
+for-retina
$map-url: sprite-url($global-retina-sprites)
$map-width: image-width(sprite-path($global-retina-sprites)) / 2
.#{$base-class}-sprites
background-image: $map-url
background-size: $map-width auto
=get-sprite($sprite)
$sprite-image: sprite-file($global-sprites, $sprite)
$width: image-width($sprite-image)
$height: image-height($sprite-image)
background-position: sprite-position($global-sprites, $sprite)
width: $width
height: $height
@robertwbradford
Copy link

This is a great piece of code. Thank you. I'm not understanding why the get-sprite mixin only sets the background-position, width, and height. Maybe I'm not understanding the use case, but I would think it would also include the background-image and background-repeat of the sprites. Are you saying it's to be included in a class that has previously extended the corresponding sprite class?

What about adding something like the following:

// sprites.sass
=sprite-background($sprite)
  @extend .#{sprite-map-name($global-sprites)}-#{$sprite}
  +get-sprite($sprite)

// example.sass
.foo
  +sprite-background(image1)

This would apply all the necessary styling to .foo, and you don't have to remember/use the full sprite class names throughout.

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