Skip to content

Instantly share code, notes, and snippets.

@stevenw00
Last active April 2, 2023 10:02
Show Gist options
  • Save stevenw00/601182f8b90f48182709 to your computer and use it in GitHub Desktop.
Save stevenw00/601182f8b90f48182709 to your computer and use it in GitHub Desktop.
Responsive sprites using grunt-spritesmith and SCSS

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;
}
}
// 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