Skip to content

Instantly share code, notes, and snippets.

@jasonlav
Forked from kevinmpowell/responsive-sprites.md
Last active March 11, 2021 21:25
Show Gist options
  • Save jasonlav/32e72a4afc348cd176dcd52cf9a45dbe to your computer and use it in GitHub Desktop.
Save jasonlav/32e72a4afc348cd176dcd52cf9a45dbe to your computer and use it in GitHub Desktop.

Easy responsive sprites with background-size 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="sprite-github"></div>
// Handlebars template that generates the scss file
{{#spritesheet}}
$total_width: {{width}};
$total_height: {{height}};
{{/spritesheet}}
{{#block "sprites"}}
{{#each sprites}}
.sprite-{{name}} {
background-size: (($total_width / {{width}}) * 100%) (($total_height / {{height}}) * 100%);
background-image: url({{{escaped_image}}});
background-position: (({{offset_x}} / ($total_width - {{width}})) * -100%) (({{offset_y}} / ($total_height - {{height}})) * -100%);
width: {{px.width}};
height: {{px.height}};
}
{{/each}}
{{/block}}
@karland
Copy link

karland commented Nov 11, 2016

If either $total-width equals {{width}} or $total-heightequals {{height}} you get a division by 0 and an error. This can happen if the sprites-file is only one image wide. To remedy this you need to change the code into

  background-position-x: if( ($total_width -   {{width}}) != 0, ({{offset_x}} / ($total_width  -  {{width}})) * -100%, 0%);
  background-position-y: if( ($total_height - {{height}}) != 0, ({{offset_y}} / ($total_height - {{height}})) * -100%, 0%);

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