Skip to content

Instantly share code, notes, and snippets.

@kevinmpowell
Forked from stevenw00/responsive-sprites.md
Last active September 14, 2016 15:12
Show Gist options
  • Save kevinmpowell/97357409b9af7625b257 to your computer and use it in GitHub Desktop.
Save kevinmpowell/97357409b9af7625b257 to your computer and use it in GitHub Desktop.

Easy responsive sprites using grunt-spritesmith and SCSS

Requires grunt-spritesmith which generates a spritesheet from a bunch of images.

This gist passes a custom template for spritesmith to generate the SCSS file.

Gruntfile.js

sprite: {
  src: "images/*.png",
  dest: "sprites.png",
  destCss: "_sprites.scss",
  padding: 2, // Due to rounding, needs some space between images
  cssTemplate: "sprites.scss.handlebars"
}

index.html

<div class="responsive-sprites">
  <img src="sprites.png" class="icon-github">
</div>
// Handlebars template that generates the scss file
.responsive-sprites {
height: auto;
overflow: hidden;
& > img {
display: block;
max-width: none;
}
}
// explanation:
// width = 100% * spritesheet width / image width
// margin-top = 100% * distance from top of sprite to image / image width
// margin-bottom = 100% * distance from bottom of sprite to image / image width
// margin-left = 100% * distance from left of sprite to image / image width
// Constants
{{#spritesheet}}
$total_width: {{width}};
$total_height: {{height}};
{{/spritesheet}}
{{#sprites}}
img.icon-{{name}} {
width: 100% * $total_width / {{width}};
margin-top: 100% * {{offset_y}} / {{width}};
margin-bottom: -100% * ($total_height - ({{y}} + {{height}})) / {{width}};
margin-left: -100% * {{x}} / {{width}};
}
{{/sprites}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment