Skip to content

Instantly share code, notes, and snippets.

@ffigiel
Last active August 29, 2015 13:56
Show Gist options
  • Save ffigiel/9316203 to your computer and use it in GitHub Desktop.
Save ffigiel/9316203 to your computer and use it in GitHub Desktop.
Flexible svg sprites

Flexible svg sprites

I've been fiddling with svg sprites a bit today, trying to handle them in such way that you could use any unit you like to specify their size. Here's what I came up with.

(You could use this method for bitmap sprites as well, but I don't see much sense in this!)

Presumptions

All images in the sprite must share the same width or height, preferably both. Note that maintaining rules for images with several different aspect ratios may be problematic.

Compatibility

Support for generated content and svg backgrounds (duh!) is required.

Todos

  • If using sass, provide an ordered list of images' filenames for generation of css classes.
.spr
width: 5rem // Default width
background-repeat: no-repeat
background-iamge: url(your/sprite.svg)
background-size: cover
&:before
content: ""
display: block
padding-top: 100% // This sets the aspect ratio. See http://www.mademyday.de/css-height-equals-width-with-pure-css.html
//
If you want to have some images with different aspect ratio in your sprite,
you can add a new class for them.
You should use only such aspect ratios that are a multiple of the base
ratio. Otherwise your images may appear distorted.
.spr--double-ratio:before
padding-top: 200%
//
Here's the nasty part. We're going to use percent values, which will need
to be rewritten every time you add/remove an image from the sprite.
*
The formula for increment step is 100 / (n-1), where n is the number of
images in your sprite.
If 100% doesn't divide nicely with your n-1 value, consider adding a few
transparent images to the sprite.
*
Below is an example set for three sprites. 100/(3-1) is 50. We're going to
start with 0 and add 50% on each step, until we reach 100%.
.spr--first
background-position: 0 0
.spr--second
background-position: 0 50%
.spr--third
background-position: 0 100%
// And here's sass casually being awesome
$sprites: first, second, third
$n: length($sprites) - 1
@for $i from 0 through $n
$s: nth($sprites, $i + 1) // Well, almost. It counts from 1, not 0.
.spr--#{$s}
background-position: 0 #{$i * 100% / $n}
// Now add some variety to your images' width and you're good to go!
.spr--64px
width: 64px
.spr--text
width: 1em
.spr--inch
width: 2.54cm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment