magnify
magnify
Home Stylus Sprite positionning with Stylus functions
category

Sprite positionning with Stylus functions

Published on May 21, 2014 by in Stylus

Stylus

There are a lot of solutions to generate sprite in Node‘s ecosystem, using ImageMagick, Grunt or Gulp.

But when you work with designers whoses export their own sprite files, you have to deal with the background-position which may be a mess depending on the file organisation.

In my case, I negociate a compromise with my Picasso: to have dedicated files for each same icons size, positioned on a width * height grid.
Finally, I only had square icons: 22*22, 30*30 and 50*50, so, I simplified the positionning using size instead of width and height in my stylus functions, but if needed, the update will be easy.

In this example, I’ll describe the 22 * 22 sprite support.

sprite file

For each sprite file, I add a class:

.i22
    background transparent url("../images/icons22.png") no-repeat
    display inline-block
    width 22px
    height 22px

To position the background image, I use a generic stylus function:

/**
 * Calculate and position an icon for a square sprite
 * @param size {Integer} 1 to n
 * @param x {Integer} 0 to n
 * @param y {Integer} 0 to n
 */
iconX(size, x, y)
    background-position unit(-1 * size * x, "px") unit(-1 * size * y, "px")

And to position the 22*22 icon, I use a dedicated stylus function:

/**
 * Calculate and position an icon for a 22*22 sprite
 * @param x {Integer} 0 to n
 * @param y {Integer} 0 to n
 */
icon22(x, y)
    iconX(22, x, y)

Example of use:
HTML

<img src="empty.gif" class="i22 sampleF" />

Stylus (CSS)

.sampleF
    icon22(2, 1)
 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 

You must be logged in to post a comment.