Skip to content

Instantly share code, notes, and snippets.

@donut
Last active August 29, 2015 14:04
Show Gist options
  • Save donut/ea9b2e36746411ae659d to your computer and use it in GitHub Desktop.
Save donut/ea9b2e36746411ae659d to your computer and use it in GitHub Desktop.
How to get Compass like sprites with Stylus and SVG

Using the grunt-dr-svg-sprites GruntJS plugin and a custom Handlebars template (below) I was able to get the basic functionality that Compass provides for PNG sprites but for SVGs.

Note that the below template is not generalized and will not work for all dr-svg-sprites configurations. It works for my setup and would probably be a good base for others.

I've included the relevant portions of my Gruntfile as well.

module.exports = (grunt) ->
theme_path = 'web/sites/all/themes/example'
modules_path = 'web/sites/all/modules'
config =
pkg: grunt.file.readJSON 'package.json'
config['svg-sprites'] =
options:
layout: "packed"
config['svg-sprites'].theme =
options:
spriteElementPath:
["#{theme_path}/images/*.svg", "#{theme_path}/images/*/*.svg"]
spritePath: "#{theme_path}/build/spritesheet.svg"
cssPath: "#{theme_path}/build/spritesheet.styl"
template: "#{theme_path}/styles/svg-sprites.hbs"
config.watch = {}
config.watch.options =
spawn: yes
interrupt: no
atBegin: yes
livereload: on
config.watch.theme =
files: ["#{theme_path}/images/*.svg", "#{theme_path}/images/*/*.svg"]
tasks: ['svg-sprites:theme']
grunt.initConfig config
grunt.loadNpmTasks 'grunt-contrib-watch'
grunt.loadNpmTasks 'grunt-dr-svg-sprites'
@require 'mixins'
{{blank_line}}
{{~#sizes~}}
svg-sprites = {
path: unquote("{{url ../svgPath ../cssPath}}"),
width: px2rem({{width}}),
height: px2rem({{height}})
}
{{blank_line}}
{{~#items~}}
svg-sprites['{{className}}'] = {
position: px2rem(-{{x}}) px2rem(-{{y}}),
width: px2rem({{width}}),
height: px2rem({{height}})
}
{{/items~}}
{{blank_line}}
svg-sprite-repeat-default = no-repeat
$svg-sprite
background: 'url(../build/%s) no-repeat 0 0' % svg-sprites.path
background-size: svg-sprites.width svg-sprites.height
svg-sprite(name, set-dimensions=false, bg-repeat=null)
@extends $svg-sprite
background-position: svg-sprites[name].position
if set-dimensions
width: svg-sprites[name].width
height: svg-sprites[name].height
if bg-repeat and bg-repeat isnt svg-sprite-repeat-default
background-repeat: bg-repeat
{{~/sizes~}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment