Skip to content

Instantly share code, notes, and snippets.

@lvisintini
Forked from yonatanmn/css sprite with sass (scss)
Last active July 17, 2017 16:37
Show Gist options
  • Save lvisintini/c04ffac154d43b7ad8de9891bc6a3ceb to your computer and use it in GitHub Desktop.
Save lvisintini/c04ffac154d43b7ad8de9891bc6a3ceb to your computer and use it in GitHub Desktop.
css sprite with sass (scss)

Stripe SASS

Usage

  1. Create a sprite of square images (if the icon is not square, save it inside a square anyway) example

  2. Define sass map with the keys specified:

$mySprite:(
  url: '../images/mySprite.png', 
  names: ('createIcon','player','bell', ...),  // names of all of the icons in sprite
  itemsInRow: 10,  //sprite structure
  numOfRows: 2
);
  1. Use it like this:
.selector{
  // sprite, name of the item, size (width and height)
  // note that adding percentage should be in a square parent parent
  @include backgroundImageBySprite($mySprite,'bell',30px)  
}

You may also load all icons directly by doing:

@include loadSpriteClasses($mySprite,'icon',30px)  

See https://codepen.io/yonatanmn/pen/LVdyYx for working demo.

@function divideEscape0($a,$b){
@if ($b ==0){@return 0}
@return $a/$b;
}
@function getImagePositionFromSprite($iconName,$sprite-name,$itemsInRow:10,$numOfRows:1){
$index: index($sprite-name,$iconName);
$row: ceil($index/$itemsInRow);
$indexInRow: $index % $itemsInRow;
@return percentage(divideEscape0(1,($itemsInRow - 1))*($indexInRow - 1)) percentage(divideEscape0(1,($numOfRows - 1))*($row - 1));
}
@mixin backgroundImageBySprite($sprite,$name,$size){
background-image: url(map_get($sprite,url));
background-position: getImagePositionFromSprite(
$name,
map_get($sprite,names),
map_get($sprite,itemsInRow),
map_get($sprite,numOfRows)
);
height: $size;
width: $size;
background-size: auto $size * (map_get($sprite,numOfRows));
}
@mixin loadSpriteClasses($sprite, $prefix, $size){
@each $current-name in map-get($sprite, names) {
.#{$prefix}-#{$current-name} {
@include backgroundImageBySprite($sprite, $current-name, $size)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment