node.js sprites generator for LESS
Requirements
less-sprites
uses ImageMagick, so install it first.
Installation
npm install less-sprites
Usage
Write a list of source images into a .json
file:
{ "files": ["icon1.png", "icon2.png"] }
Create the sprite:
less-sprites my-sprite.json
There are more options you can specify:
{
"direction": "right|bottom",
"dir": "icons-sprite",
"files": ["icon1.png", "icon2.png"],
"sprite": "icons-sprite.png",
"httpPath": '/images',
"spacing": 50,
"retina": true,
"less": "../less/icon-sprite.less"
}
Using the sprite in your LESS stylesheet
less-sprites my-sprite.json
creates two files:
my-sprite.png
- the final sprite imagemy-sprite.less
- positions of the images inside the sprite
In your stylesheet you target the original image, not the sprite; it will be translated during compilation.
CSS without less-sprites
.icon-first {
background: url('/images/icons_sprite/icon1.png');
}
.icon-second {
background: url('/images/icons_sprite/icon2.png');
}
LESS with less-sprites
@import "icons/icons-sprite.less"
.icon-first {
.sprite('icon1.png');
}
.icon-second {
.sprite('icon2.png', true);
}
which is later compiled into final CSS:
.icon-first {
background: url("/images/icons-sprite.png") 0px 0px;
background-repeat: no-repeat;
background-position: 0px 0px;
}
.icon-second {
height: 118px;
width: 69px;
background-repeat: no-repeat;
background: url("/images/icons-sprite.png") 0px -20px;
}
Now when you need to add a new image to the sprite, you simply it to the .json
file and call less-sprites
.
No extra work is needed in your stylesheets.
LESS with less-sprites
and enabled retina in the sprite file
@import "icons/icons-sprite.less"
.icon-first {
.sprite('icon1.png');
}
.icon-second {
.sprite('icon2.png', true);
}
which is later compiled into final CSS:
.icon-first {
background: url("/images/icons-sprite.png") 0px 0px;
background-repeat: no-repeat;
background-position: 0px 0px;
}
.icon-second {
height: 118px;
width: 69px;
background-repeat: no-repeat;
background: url("/images/icons-sprite.png") 0px -20px;
}
@media (-webkit-min-device-pixel-ratio: 1.5), (min--moz-device-pixel-ratio: 1.5), (-o-min-device-pixel-ratio: 3/2), (min-device-pixel-ratio: 1.5) {
.icon-first {
background-image: url("/images/sprite-specs2x.png");
background-position: 0px 0px;
background-size: 270px auto;
}
}
Name conflicts
If you @import
several sprites into global namespace there is a possibility of name conflict (imagine referencing two images from two different places as ../image.png
). The best way to avoid this is to always import inside a scope:
.my-icons {
@import "...";
.icon-first {
.sprite('...');
}
}
License
The MIT License.