Skip to content

Instantly share code, notes, and snippets.

@arminrosu
Last active November 15, 2015 08:42
Show Gist options
  • Save arminrosu/9370508 to your computer and use it in GitHub Desktop.
Save arminrosu/9370508 to your computer and use it in GitHub Desktop.
Compass SVG Sprite via Grunt

Compass SVG Sprite via Grunt

Generate a svg sprite in grunt and corresponding values for use in sass (_svg_sprites.scss), sass functions (_mixins.scss) that mimic compass sprite functions.

Why

I wanted to use svg sprites in compass, specifically needing sprite-position(). Unfortunately, only PNG sprites are supported so far.

Since I'm using Grunt anyway, I looked for alternatives. SVG Sprite seemed like the best option for me and contains SVGO already.

// same use instructions as sprite-position()
// $map is the sprite-map generated through svg-sprite
@function svg-sprite-get($map, $sprite) {
@each $s in nth($map, 2) {
$s-name: nth($s, 1);
@if $s-name == $sprite {
@return $s;
}
}
}
@function svg-position($map, $sprite, $offset-x: 0, $offset-y: 0) {
$s: svg-sprite-get($map, $sprite);
// subtract svg padding from position
$s-position-x: nth($s, 4) - nth($s, 6);
$s-position-y: nth($s, 5) - nth($s, 6);
@return round($s-position-x + $offset-x) round($s-position-y + $offset-y);
}
@function svg-url($map) {
// This is something you'll probably want to customize
@return unquote("url(../") + nth($map, 1) + unquote(")");
}
@function svg-width($map, $sprite) {
$s: svg-sprite-get($map, $sprite);
@return nth($s, 2);
}
@function svg-height($map, $sprite) {
$s: svg-sprite-get($map, $sprite);
@return nth($s, 3);
}
// Sample Output
// sorry, SASS maps are coming in 3.3
$icon-map: (
"images/sprite.svg",
(
// sprite, width, height, position-x, position-y, padding
(archive, 16px, 14px, 0px, 0px, 10px),
(arrow-down, 10px, 18px, -36px, -34px, 10px),
(arrow-left, 18px, 10px, -66px, -72px, 10px)
)
);
svgsprite: {
options: {
padding: 10,
prefix: 'icon',
layout: 'diagonal', // OR 'vertical' OR 'horizontal'
render: {
css: false,
compass: {
template: 'path/to/template.js',
dest: 'path/to/_svg_sprites.scss'
}
},
spritedir: 'where/to/save/output'
},
build: {
flatten: true,
src: 'path/to/svg-sprites',
dest: ''
}
}
${{prefix}}-map: (
"{{sprite}}",
(
// sprite, width, height, position-x, position-y, padding
{{#svg}}{{#selector}}({{name}}, {{width}}px, {{height}}px, {{positionX}}px, {{positionY}}px, {{padding}}px){{/selector}}{{^last}},
{{/last}}{{/svg}}
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment