Skip to content

Instantly share code, notes, and snippets.

@stikoo
Created April 16, 2015 08:46
Show Gist options
  • Save stikoo/f09c21bb12fee170dbba to your computer and use it in GitHub Desktop.
Save stikoo/f09c21bb12fee170dbba to your computer and use it in GitHub Desktop.
// the $svg-sprite var is generated by the gulp-svg-sprites module
// and is a sass map containing all the svg sprite info.
$sprite: map-get($svg-sprite, sprite) !default;
$sprite-padding: map-get($sprite, padding);
$pngSpriteClass: '.no-svg';
// function for merging sass maps
@function extend($map, $ext-map) {
@return map-merge($map, $ext-map);
}
// Gets an attribute from the sass map
@function sprite-attr($icon, $attr) {
$icon: map-get($svg-sprite, $icon);
@return map-get($icon, $attr);
}
// retrieve the icons attributes
@function icon-attr($icon) {
$attr: (
width: sprite-attr($icon, width),
height: sprite-attr($icon, height),
x: (sprite-attr($icon, backgroundX) - map-get($sprite-padding, left)),
y: (sprite-attr($icon, backgroundY) - map-get($sprite-padding, top))
);
@return $attr;
}
// A sprite plugin the allows for configuration to be
// passed in as a sass map.
// The mixin allows offsetting, scaling and outputing
// css without dimensions etc
@mixin sprite($icon, $conf: ()) {
$conf: extend((
type: all,
offset-x: 0,
offset-y: 0,
), $conf);
$iconAttr: icon-attr($icon);
$type: map-get($conf, type);
$widthRatio: 1;
$heightRatio: 1;
// Outputs dimensions
@if $type == all or $type == size {
@if map-get($conf, width) {
width: map-get($conf, width)
}
@else {
width: map-get($iconAttr, width);
}
@if map-get($conf, height) {
height: map-get($conf, height)
}
@else {
height: map-get($iconAttr, height);
}
}
// Outputs background position
@if $type == all or $type == bg {
@if map-get($conf, width) {
$widthRatio: map-get($conf, width) / map-get($iconAttr, width);
}
@if map-get($conf, height) {
$heightRatio: map-get($conf, height) / map-get($iconAttr, height);
}
$pos-x: (map-get($iconAttr, x) + map-get($conf, offset-x)) * $widthRatio;
$pos-y: (map-get($iconAttr, y) + map-get($conf, offset-y)) * $heightRatio;
background-position: $pos-x $pos-y;
}
// Outputs background size and image
@if not $type == size {
// compare that ratio difference between the desired size and the actual size,
// then apply this ratio to the background size
background-size: (map-get($sprite, width) * $widthRatio) (map-get($sprite, height) * $heightRatio);
background-image: url(map-get($sprite, svgPath));
// with png fallback
@if $pngSpriteClass {
@if not $type == size {
#{$pngSpriteClass} & {
background-image: url(map-get($sprite, pngPath));
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment