How can I automatically generate sprites for my less file?

css, less

Solution

You can separate your sprite CSS selectors into their own file that's generated at the same time as your sprite sheet. I use SpriteRight but there any many ways to skin that cat. Here's a command line tool called Glue if you prefer that. Once you have your sprite Less/CSS file you then import it back into your main Less file, and it should work.

So your setup might look like this:

- /less

- main.less

- sprite.less

- /css

- main.css (compiled & concatenated Less files)

- /img

- /_for-sprites

- ... (the images that comprise your sprite sheet)

- sprite.png

main.less:

... (snip) ...
@import 'sprite.less';
... (snip) ...

sprite.less (generated by a utility as linked above):

... (snip) ...
.icon1 { background-position: 0 0; }
.icon2 { background-position: 20px 20px }
... (snip) ...

I hope my explanation makes sense. I do something very similar to this every day and it works great.

Problem

I have a project with `less` files which reference images via URLs. The project is delivered to the user as a single page application, with all JS minfiied and sent as one file. However, images are sent in separate files. To eliminate this latency, I want to deliver the images in one file. How can I (in a non-manual manner) sprite the images, and alter the `less` to refere to the sprited images?

Original source