Skip to content

Instantly share code, notes, and snippets.

@yonatanmn
Last active July 17, 2017 15:14
Show Gist options
  • Save yonatanmn/c0374aa4a4475515a9cd to your computer and use it in GitHub Desktop.
Save yonatanmn/c0374aa4a4475515a9cd to your computer and use it in GitHub Desktop.
css sprite with sass (scss)
//usage is pretty simple:
//1. create a sprite of square images (if the icon is not square, save it inside a square anyway):
// example: http://glue.readthedocs.org/en/latest/_images/famfamfam2.png
//2. define sass map with the keys specified:
$mySprite:(
url: '../images/mySprite.png',
names: ('createIcon','player','bell','notifications','icon13','icon15'...), //names of all of the icons in sprite
itemsInRow: 10, //sprite structure
numOfRows: 2
);
//3. use it like this:
.selector{
@include backgroundImageBySprite($mySprite,'bell',30px) //sprite, name of the item, size (width and height) - note that adding percentage should be in a square parent parent
}
//=======================================================================//
//the mixin (and functions) are defined here:
@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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment