Menu Search
Jump to the content X X
Smashing Conf Barcelona

You know, we use ad-blockers as well. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. our upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

CSS Sprites Revisited

I’m pretty confident that I won’t surprise anyone here by saying that CSS sprites have been around for quite a while now, rearing their somewhat controversial heads in the Web development sphere as early as 2003.

Still, the CSS sprite hasn’t truly found its way into the everyday toolkit of the common Web developer. While the theory behind CSS sprites is easy enough and its advantages are clear, they still prove to be too bothersome to implement, especially when time is short and deadlines are looming. Barriers exist to be breached, though, and we’re not going to let a couple of tiny bumps in the road spoil the greater perks of the CSS sprite.

Further Reading on SmashingMag: Link

If you want more background information on best practices and practical use cases, definitely read “The Mystery of CSS Sprites: Techniques, Tools and Resources1.” If you’re the defensive type, I would recommend “CSS Sprites: Useful Technique, or Potential Nuisance?2,” which discusses possible caveats.

I won’t take a stance on the validity of CSS sprites. The aim of this article is to find out why people still find it difficult to use CSS sprites. Also, we’ll come up with a couple of substantial improvements to current techniques. So, start up Photoshop (or your CSS sprite tool of choice), put on your LESS and Sass hats, and brush up your CSS pseudo-element skills, because we’ll be mixing and matching our way to easier CSS sprite implementation.

The Problem With CSS Sprites Link

While Photoshop is booting, take a moment to consider why CSS sprites have had such a hard time getting widespread acceptance and support. I’m always struggling to find the correct starting position for each image within a sprite. I’ll usually forget the exact coordinates by the time I need to write them down in the style sheet, especially when the image is located at x:259, y:182 and measures 17×13 pixels.

I’m always switching back and forth between Photoshop and my CSS editor to write down the correct values, getting more and more frustrated with every switch. I know software is out there specifically tailored to help us deal with this, but I’ve never found an application that lets me properly structure its CSS output so that I can just copy and paste it into my CSS file.

Another important thing to realize is that CSS sprites are meant to be one part of our website optimization toolkit. Many of the people who write and blog about CSS sprites are comfortably wearing their optimization hats while laying out best practices, often going a little overboard and losing track of how much effort it requires to implement their methods of choice.

This is fine if you’re working on an optimization project, but it becomes counterproductive when you need to build a website from scratch while fighting tight deadlines. If you have time to truly focus on implementing a CSS sprite, it’s really not all that hard; but if you have to juggle 50 other priorities at the same time, it does turn into a nuisance for many developers. With these two factors in mind, we’ll try to find a way to make image targeting easier, while coming to terms with the fact that sometimes we have to sacrifice full optimization in the name of ease of development.

CSS sprites in the wild: Amazon, Google and Facebook.
CSS sprites in the wild: Amazon, Google and Facebook.

Preparing The Sprite Link

If you look online for examples of CSS sprites, you’ll see that most are optimized for an ideal use of real estate—gaps between images are kept to a minimum in order to keep the load of the entire sprite as low as possible. This reduces loading time considerably when the image is first downloaded, but it also introduces those horrible image coordinates that we mentioned earlier. So, why not take a slightly different approach? Let’s look for an easier way to target images while making sure the resulting sprite is not substantially bigger than the sum of its individual images.

Rather than try to stack the images in such a way that makes the resulting sprite as small as possible, let’s try a different layout. Instead of a random grid, we’re going to build a nice square grid, reserving the space of each square for one image (although larger images might cover multiple squares). The goal is to be able to target the starting point of every image (top-left corner) with a very simple mathematical function.

The size of the grid squares will depend on the average dimension of the images that you’ll be spriting. For my website, I used a 32×32 pixel grid (because only one image exceeds this dimension), but grid sizes will vary according to the situation. Another thing to take into account is the image bleeding that can occur when zooming a page; if you want to play it safe, add a little padding to each image within the sprite. For extra optimization, you could also use a rectangular grid instead of a square grid, further reducing any wasted space; while a tad more complex, this isn’t much different from what we’ll be doing. For this article, though, we’ll stick with the square grid.

Preparing The Sprite: A Photoshop Bonus Link

I’m no designer, so I’m not sure how applicable this section is beyond the realm of Photoshop, but there are still some noteworthy improvements that can be made before we get to the actual code. First of all, visualizing the grid can be of great help. Photoshop has guides to do this (so you don’t actually have to include the markers in your sprite), with the added bonus that layers will snap to these guides (making pixel-perfect positioning of each individual image much easier).

Manually adding these guides can be somewhat of a drag, though. Luckily, a colleague of mine (hats off to Filip Van Tendeloo) was kind enough to write and share a little Photoshop script3 that builds this grid of guides automatically based on the base size of your square. Pretty convenient, no? Just download the script, save it in the PresetsScripts directory, and choose File → Scripts → Sprite Grid from the Photoshop menu.

Finally, to really finish things off, you can add numbers to the x and y axes of your grid so that you can easily pinpoint every square in the grid. Don’t add these numbers to the actual sprite, though; just copy the sprite into a new image and add them there. These numbers are just for reference—but trust me, they will definitely come in handy in a minute.

Example of a reference image.
Example of a reference image.

If you can’t (or don’t want to) use preprocessing languages such as LESS and Sass, just add the coordinates of each square instead.

LESS And Sass To The Rescue Link

With all of the images on the same square grid, we can now easily compute the top-left coordinate of each image (this coordinate is the exact match needed for the background-position values to reposition the sprite). Just take the base size of the grid and multiply it by the numbers that you just added to your reference image. Say you need to target the image at a position of (5,3), and your grid size is 32 pixels; the top-left position of your image will be 32 × (5,3) = (160,96). To add these values to your CSS file, just use their negative equivalents, like so:

background-position: -160px -96px;

Leave your calculator where it is for the time being, because it would be too much of a hassle. If computers are good at anything, it’s doing calculations, so we’re going to make good use of that power. Plain CSS doesn’t allow us to do calculations (yet), but languages like LESS and Sass were made to do just that. If you need more background information, check out the article “An Introduction to LESS and Comparison to Sass4.” While both languages offer similar functionality, their syntaxes are slightly different. I’m a LESS man myself, but if you’re used to Sass, converting the following examples to Sass code shouldn’t be too hard. Now for some advanced CSS magic:

@spriteGrid: 32px;
.sprite(@x, @y) {
   background: url(img/sprite.png) no-repeat;
   background-position: -(@x*@spriteGrid) -(@y*@spriteGrid);

Nothing too exciting so far. First, we’ve defined the grid size using a LESS variable (@spriteGrid). Then, we made a mixin that accepts the numbers we added to the reference image earlier. This mixin uses the grid variable and the image’s coordinates to calculate the base position of the image that we want to target. It might not look fancy, but it sure makes the basic use of sprites a lot easier already. From now on, you can just use .sprite(1,5), and that’s all there is to it. No more annoying calculations or finding random start coordinates.

Of course, the mixin above only works in our somewhat simplified example (using a square grid and just one sprite). Some websites out there are more complex and might require different sprites using rectangular grids for additional optimization. This isn’t exactly impossible to fix with LESS, though:

.spriteHelper(@image, @x, @y, @spriteX, @spriteY) {
   background: url("img/@{image}.png") no-repeat;
   background-position: -(@x*@spriteX) -(@y*@spriteY);
.sprite(@image, @x, @y) when (@image = sprite1), (@image = sprite3){
   @spriteX: 32px;
   @spriteY: 16px;
   .spriteHelper(@image, @x, @y, @spriteX, @spriteY);
.sprite(@image, @x, @y) when (@image = sprite2){
   @spriteX: 64px;
   @spriteY: 32px;
   .spriteHelper(@image, @x, @y, @spriteX, @spriteY);

Yes, this looks a bit more daunting, but it’s still pretty basic if you take a minute to understand what’s going on. Most importantly, the added complexity is safely hidden away inside the LESS mixins, and we’re still able to use the same sprite mixin as before, only now with three parameters in total. We’ve just added an image parameter so that we can easily determine which sprite to use each time we call our mixin.

Different sprites might have different grid dimensions, though; so, for each grid dimension, we need to write a separate LESS mixin. We match each sprite to its specific dimension (the example above handles three different sprites and matches it to two different grid dimensions), and we define the dimensions (@spriteX and @spriteY) locally in each mixin. Once that is done, we offload the rest of the work to a little .spriteHelper mixin that does all of the necessary calculations and gives us the same result as before.

The “guards” (as LESS calls them—characterized by the keyword “when”) are quite new to the LESS vocabulary, so do make sure you’re using the latest version of the LESS engine if you attempt to run this yourself. It does offer a great way to keep the sprite mixin as clear and concise as possible, though. Just pass the sprite you want to use to the sprite mixin, and LESS will figure out the rest for you.

Common CSS Sprite Use Cases Link

With these mixins at our disposal, let’s see what different CSS sprite use cases we can identify and find out whether capturing these use cases in additional LESS mixins is possible. Once again, in order to minimize complexity in the upcoming sections, we’ll assume you’re working with a square grid sprite. If you need a rectangular grid, just add the image’s parameter to the LESS mixins we’ll be working with, and everything should be fine.

For each use case, we’ll define two mixins: one with and one without height and width parameters. If you’re like me and you keep misspelling the height and width keywords, the second mixin might come in handy. It does leave you the responsibility of learning the correct order of the parameters, though. LESS allows you to define these mixins in the same document, however, so there’s really no harm in listing them both, picking whichever is easiest for you.

1. Replaced Text Link

This is probably the easiest use case, occurring when we have an html element at our disposal that can be given a fixed dimension (in order to ensure we can hide the unwanted parts of the sprite). We’ll also be hiding the text inside the html element, replacing it with an image from our sprite. Typical examples of this use case are action links (think delete icons, print links, RSS icons, etc.) and headings (although CSS3 and Web fonts are quickly making this technique obsolete).

   text-indent: -999em;
   letter-spacing: -999em;
   overflow: hidden;
.spriteReplace(@x, @y) {
   .sprite(@x, @y);
.spriteReplace (@x, @y, @width, @height) {
   .sprite(@x, @y);
   width: @width;
   height: @height;

The spriteReplace mixin simply wraps our former sprite mixin and adds a small helper mixin to hide the text from view. It’s pretty basic, but it does save us the trouble of adding the .hideText mixin manually for every instance of this use case.

Using sprites for replaced elements.

In the example above, we have a list of sharing options. For whatever reason (theming or just personal preference), let’s say we decide to use CSS backgrounds instead of HTML images. Nothing to it with the mixins we just created. Here’s the code (assuming we’re using the reference image shown earlier):

<ul class="sharing">
   <li class="twitter"><a href="#">Share [article’s title] on Twitter</a></li>
.sharing .twitter a {
   .spriteReplace(0, 0, 32px, 32px); display:block;

2. Inline Images Link

For the second use case, we’ll tackle inline images. The main problem we’re facing here is that we won’t be able to put fixed dimensions on the html element itself because we’re dealing with variable-sized content. Typical uses of inline images are for icons next to text links (for example, external links, download links, etc.), but this method can also be used for any other item that allows text to be wrapped around a sprite image.

.spriteInline(@x, @y) {
   .sprite(@x, @y);
   display: inline-block;
   content: "";

.spriteInline(@x, @y, @width, @height) {
   .sprite(@x, @y);
   display: inline-block;
   content: "";
   width: @width;
   height: @height;

We might be lacking a structural element to visualize our image, but 2011 taught us that pseudo-elements are the perfect hack to overcome this problem (Nicolas Gallagher’s eye-opening article on using pseudo-elements for background images5 explains everything in detail). This is why the spriteInline mixin was especially developed to be used within a :before or :after selector (depending on where the image needs to appear). We’ll add an inline-block declaration to the pseudo-element so that it behaves like an inline element while still allowing us to add fixed dimensions to it, and we’ll add the content property, which is needed just for visualizing the pseudo-element.

Using sprites for inline images.

The example above shows a list of affiliate links. The design demands that each link be limited to one line, so we can safely use the .spriteInline mixin to display the icons in front of each link:

<ul class="affiliates">
   <li class="amazon"><a href="#">Buy on</a></li>
.affiliates .amazon a:before {
   .spriteInline(4, 1, 22px, 16px);

3. Padded Images Link

The third and final use case comes up when text isn’t allowed to wrap around a sprite image. Typical examples are list items that span multiple lines, and all kinds of visual notifications that bare icons. Whenever you want to reserve space on a multi-line element to make sure the text lines up neatly next to the image, this is the method you’ll want to use.

.spritePadded(@x, @y) {
   .sprite(@x, @y);
   position: absolute;
   content: "";
.spritePadded(@x, @y, @width, @height) {
   .sprite(@x, @y);
   position: absolute;
   content: "";
   width: @width;
   height: @height;

Again we’ll try our luck with pseudo-elements; this time, though, we’ll be performing some positioning tricks. By applying a position: absolute to the pseudo-element, we can place it right inside the space reserved by its parent element (usually by applying padding to the parent—hence, the name of the mixin). The actual position of the image (the left, right, top and bottom properties) is not added to the spritePadded mixin and should be done in the selector itself to keep things as clean and simple as possible (in this case, by maintaining a low parameter count).

Because we’re using absolute positioning, either the :before or :after pseudo-element will do the job. Keep in mind, though, that the :after element is a likely candidate for CSS clearing methods, so if you want to avoid future conflicts (because the clearing fix won’t work if you add a position: absolute to the :after pseudo-element), you’d be safest applying the sprite style to the :before element.

Using sprites for padded elements.

Let’s assume we need to indicate that our article is available in other languages (probably on a different page or even website). We’ll add a little notification box, listing the different translations of the current article. If the text breaks onto a second line, though, we do not want it to crawl below our little icon, so we’ll use the spritePadded mixin:

<section class="notification translated">
   <p>Translation available…</p>
.translated p {
   padding-left: 22px;
   position: relative;
.translated p:before {
   .spritePadded(5, 5, 16px, 14px);
   left: 0;
   top: 0;

The Ideal Sprite Link

So, have we achieved CSS sprite wizardry here? Heck, no! If you’ve been paying close attention, you might have noticed that the use cases above offer no solution for adding repeating backgrounds to a sprite. While there are some ways around this problem, none of them are very efficient or even worthy of recommendation.

What CSS sprites need in order to truly flourish is a CSS solution for cropping an image. Such a property should define a crop operation on a given background image before the image is used for further CSS processing. This way, it would be easy to crop the desired image from the sprite and position it accordingly, repeating it as needed; we’d be done with these :before and :after hacks because there wouldn’t be anything left to hide. A solution has been proposed in the Editor’s Draft of the CSS Image Values and Replaced Content Module Level 36 (section 3.2.1), but it could take months, even years, for this to become readily available.

For now, the LESS mixins above should prove pretty helpful if you plan to use CSS sprites. Just remember to prepare your sprite well; if you do, things should move ahead pretty smoothly, even when deadlines are weighing on you.


Footnotes Link

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6

↑ Back to top Tweet itShare on Facebook

Niels Matthijs spends his spare time combining his luxury life with the agonizing pressure of blogging under his Onderhond moniker. As a front-end developer he is raised at Internet Architects, investing plenty of time in making the web a more accessible and pleasant place.

  1. 1

    Great article, but when talking about LESS, SASS and Spriting and not mentioning the beauty of automagical Compass Sprites seems a bit off.
    I mean at least for users of SASS – it’s no problem turning Compass on (whether you’re using an app to compile or the terminal), and when compass is on – it automagically generates a sprite from all your images in the specified directory. I never even open photoshop to do it anymore.

    • 2

      Rizky Syazuli

      April 11, 2012 8:51 am

      agree.. with Compass+Sass it only takes two lines of code. here’s the tutorial for creating sprites with Compass:

      • 3

        Yes, not mentioning compass is a big miss here

        • 4

          Niels Matthijs

          April 12, 2012 9:39 am

          I did read up on SASS/Compass and while very interesting, it’s not a methodology, rather an implementation on a single framework. Definitely handy when using SASS (and it could’ve been mentioned in the article as an afterthought), but far too flimsy to build an entire workflow on.

          The thing is that the point of this article still stands even when you leave the whole LESS thing out of it. Maybe the focus on the LESS/SASS thing shifted the focus of the article in the wrong direction, then again people who prefer LESS could still benefit from the functions.

          Thanks for the heads-up though!

  2. 5

    I have to manage a big sprite, and I found a solution which perfectly fits my needs
    I have several photoshop files, some are messy, but it’s not a problem, then i slice everything i want. So I end with a lot of little images.
    Then, I import all the pack in this shiny little app, and TADA : it compacts me all the images to make the most little output image possible, and it create the CSS file linked to it (each icon with a classname equal to the slice name).

    (Note that the app is still a bit crashy, I hope it will be resolved, but my output files are ok each time)

  3. 6

    Nice post :)
    The mixins are indeed a nice addition in order to stop doing the maths.

    For Sass+Compass users though, working with sprites is really a piece of cake, and all those mixins are still too much work ;)
    With Compass, you basically just have to put all the images you want in the same folder and you’re good to go.
    Compass will dynamically build the sprite as you want and will know for you the position of each image in the sprite. A bunch of mixins and helpers are already at your disposal to work.

    This is one of the key features of Sass/Compass compared to Less for me.

  4. 7

    I strongly disagree. Making extra large images and relying on a CSS preprocessor in order to more easily remember a few numbers is overkill. The load time along is enough to kibosh this approach. All you should need is the info panel in Photoshop and a few guides to do the job. Don’t over-complicate things.

    • 8

      ^ That’s only true if you compile your less file in real time in production which I don’t think is a good idea. And as said below, spriting your image in Photoshop removes the flexibility of having your images as they are.


      Nice article but as mentioned, it’s kind of obvious that you’re a LESS developper before being SASS one because SASS and Compass offer something much more simpler than that.

      You put your images in a folder, @import that folder in your sass code, and it will automatically generate a sprite from that folder, with corresponding mixins to call each image by their name.

      Like this :

      @import interface/*.png


      And it will automatically select the right spot in the sprite to include. It even manages hover and active states automatically. You can configure your generated sprite as you wish etc.
      Really, LESS gained a lot of features recently but on some fields it will never be as powerful as what both SASS and Compass combined offer. Take a look at the Compass Sprite documentation to see more what I mean :

      • 9

        Compass sounds cool… I really don’t understand why they wouldn’t want to support LESS users as well :(

        • 10

          Because SASS has built-in conditions and loops, such as @if, @for, @while, @else, @each, etc, as well as lists and associative lists. Those are at the core of Compass and allow its flexibility, without them none of it would exist, and unfortunately LESS has none of those syntaxes.

    • 11

      I have to agree with you on this. Ok it requires a bit of concentration but it’s not such a hassle to tae the lelection tool and make a rectangle from the top left of your canevas to the top left of your icon.

      I’ts an interesting technique indeed and it might be useful on some cases. But in my own opinion it gets thing more complicated that they really are.

    • 12

      If you’re building your sprite in Photoshop, you can create slices around each image in your sprite. Then when you open the dialog box for each slice, there are boxes with the x-coordinate, y-coordinate, width, and height of the slice. In your CSS, just make the x and y coordinates negative. Done. You don’t have to measure each time or try to remember all the coordinates or sizes.

    • 13

      It was actually worse than that, too. I made a thared to introduce myself and show my sprite, and immediately got comments saying PUT IT IN THE COMPLETED SPRITES FOR USE THREAD , which doesn’t make sense, and was done so without grace or so much as a hello a You get the picture. Oh well. Seems like the developers who actually make the game are really nice though, just the forum-goers who aren’t so friendly.

  5. 14

    Christian Engel

    April 11, 2012 5:49 am

    We had almost the same experience as you described in your first paragraph.
    It ist one of the most unpleasant tasks to build a spritemap with photoshop and a editor tool, since you always have to switch between them and keep positions and dimensions in mind.
    Especially looking up positions and dimensions of the sprites is a hard job with photoshop.

    So we decided to leave photoshop completely out of the process.
    You should definitely have a look at
    Its a free HTML5 web-app and makes building CSS spritemaps finally a fun job to do.
    I really wonder why you had not heard about it in the last weeks!

    Give it a try and tell us what you think about it ;)

    • 15

      Have a look at what?

      • 16

        I think SM is removing links from comments or something. There are a few comments missing references to what they are talking about.

        • 17

          Christian Engel

          April 17, 2012 7:30 am

          Yeah, I originally linked to – the link got removed, I don’t know why…

  6. 18

    Great article. Unfortunately I have been receiving errors while trying to use the sprite grid script:

    Error 21: undefined is not an object (Line: 7)

    Is it intended for a particular version of Photoshop?

    • 19

      Niels Matthijs

      April 11, 2012 8:55 am

      We’re looking into it, but the function should be supported from CS2 and up. It could be that older versions of PS might be giving us trouble though.

      • 20

        I’m using CS4

      • 21

        Jon-Paul LeClair

        April 12, 2012 7:20 am

        CS3 Here… looking at the CS3 scripting guide… there’s no mention of the “.guides” namespace. So the linked script won’t work.

    • 22

      I updated the Photoshop script to work in at least CS4 (I don’t have any older versions to try out, sorry).

      Disclaimer: None of the code is mine, I just hacked a new function together

    • 23

      Didn’t have luck with Sprite Grid either, nor the @James Burke solution.

      Here’s a tidy extension for Photoshop grids:

  7. 24

    I’m getting an error when running the photoshop script: Error 21: undefined is not an object. Line:7 -> doc.guids.add(Direction.VERTICAL, i * columnWidth);

  8. 25

    Peter Müller

    April 11, 2012 6:03 am

    Having your original images in a sprite sheet during development is an ugly hack that makes a lot of things more difficult for both the graphics designer and the web developer. The individual images are suddenly no longer available, making reuse impossible, making version control difficult, making image optimization more difficult etc. Further more you will always get in trouble with to much unused space in the sprite sheet, and having to do a lot of reorderings when some images are replaced, change dimensions etc.

    The real way to solve this problem is to keep using the original individual and non-space-optimized images during development and to introduce a build step that generates your sprite sheet and replaces the relevant css to use the generated sprite sheets. This gives you a lot of extra freedom because you no longer have to think about background offsets, sprite sheet rearrangements, optimization into seperate reduced color palette sprites etc. All images will be available in their original unaltered an unoptimized form, which means you can experiment with optimization in your build step without changing anything in your actual image or css. And of course it’s much easier to debug.

    Since most developers that need to do hard core optimizations, like sprites to reduce http requests, will have a build step for crushing their css and javascript anyway, adding automation of spriting into the mix is not that big of a leap. But it makes a huge difference to the work environment for the designer and the developer during implementation.

    The company I work for has open sourced the build system we developed for creating large web applications. Apart from all the optimizations that you would expect with minification and bundling, it also adds automated spriting, image optimization with pngcrush, pngquant, optipng and allows you to define several sprite sheets so you could optimize for reduced color palettes with pngquant, thus taking total image size much lower than a single sprite sheet ever would. The recipe for these optimizations is defined through vendor specific css properties, so it’s actually valid css, and thus you can debug on the unbuilt files during development.

    As an added bonus the build system will also automatically base64 encode and inline css images in case they are only referenced once and are within a sane boundary in dimensions, thus sometime even removing your need for a sprite sheet completely.

    If anyone is interested, take a look at

    The post process optimization syntax hasn’t been documented yet, but the spriting syntax is described in the readme.

    The complete build system the spriting system is a part of is also available, and can be highly recommended if you haven’t already implemented an automated optimization build step into your workflow

    An example of a page that uses all aspects of this automated spriting and image optimization can be found on the default page my employer puts on new blank web spaces. This one is blank for now

    • 26

      Rizky Syazuli

      April 11, 2012 8:57 am

      seems that the link to the open source repo you’ve mentioned has been stripped from the comment. your company’s build system sounds awesome..

      • 27

        Peter Müller

        April 11, 2012 11:41 pm

        Indeed it seems so. I wonder how they expect comments to be useful if noone can link to external resources.

        My companys build system is called Assetgraph-builder, and is the first hit for me on google and on github. The sprite part of it is called Assetgraph-sprite. That should hopefully be enough for you guys to find the resources with a little manual work.

        The example page that I tried linking to is jimmyborg dot net

        • 28

          Rizky Syazuli

          April 12, 2012 2:22 am

          thx Peter, i found it. lots of interesting stuff there. will try it out soon..

  9. 29

    Shane Murphy

    April 11, 2012 6:06 am

    Nice little tutorial… liking the use of LESS for the calculations :) I found recently, which is a free tool that creates sprites and css automatically which I thought was pretty cool.

  10. 30

    Aljan Scholtens

    April 11, 2012 6:08 am

    Hi, nice post, I’ve always worked with image sprites, but lately I’m having serious troubles with sprites because I work entirely responsive, working with em units and make the images beautiful on retina displays. What would you suggest to do for me and a lot of other designers? :)

    • 31

      I think you could use the background-size property but it isn’t supported on some browsers.

      • 32

        Aljan Scholtens

        April 19, 2012 11:03 pm

        If I would use background-size on a sprite it would just break, it would show all images in the sprite if I’m using cover or 100%.

        I also think every screen will get more pixels in the near future (like Retina displays), so this should set us thinking about sprites, larger images (standard?) etc.

    • 33

      Aljan nailed it for me. I used to use Sprites for everything, but with responsive and mobile sites, I find them to make the process much harder. background-size is money, but super complicated with sprites.

  11. 35

    Frank Broersen

    April 11, 2012 6:30 am

    Why not let SASS Generate the complete sprite for you?

  12. 36

    Felix Eggbert

    April 11, 2012 6:38 am

    Why not use a tool like that makes things easy…?

  13. 37

    Mike Robinson

    April 11, 2012 6:47 am

    Nice combination of LESS and advanced planning, it solves a problem a lot of designers seem to struggle with. Have you also considered reviewing automated CSS Sprite generators? While they tend to be less efficient, they do allow you to use traditional layout methods and still gain the majority of the performance boost on production.

  14. 38

    Fear not and use this

    It generates CSS file for you out of your images. That’s right, you don’t have to right your own CSS. Even if you change your pictures’ size, remove/add them to the collection, you can easily update your previously exported CSS.

  15. 39

    Niels Matthijs

    April 11, 2012 9:03 am

    As a general reaction to automatic sprite generators:

    I’ve tried a few, but found none that could output decent css rules.

    I’m not really sure about the SASS implementation, but if it could dynamically find and rewrite the background rules that would be impacted by the sprite while at the same time generating the sprite from a specific folder, then yeah … that sounds pretty cool.
    Now it seems to rely on functions and file names, which is promising, but still somewhat of a drag.

    Peter Müller: sounds like a great solution, I will definitely look into it. One thing to check is whether the setup of the system is actually worth the trouble and whether it integrates will in existing workflows.

  16. 40

    I’ve been using Atlas CSS for this type of things, and it works like a charm.
    Just put all your icons on a folder, run the Photoshop script, and it generates a CSS with the coordenates and size of each icon, using the original filename as CSS selector.

    Have to add some icons? No problem, add them to the folder, run the script again, and copypaste the generated CSS, no more dealing with coordenates or sizes.

    If someone ports this to Fireworks, I’ll be the most happy developer in the world :P

    P.S. If you don’t want to have all the icons on separate files, you can use Layer Cake to generate them from your unique PSD file:

    P.S. 2 Once again, If someone ports Layer Cake, or even combine those two steps on one Fireworks script, I’ll be happy forever :P

  17. 41

    Daniel Adrian

    April 11, 2012 10:38 am

    You could use SmartSprites

  18. 42

    If IE7 is not a concern, inline your images in your CSS as base64 encoded data URI:s instead of using sprites.

    There are multiple tools available, but I just keep a folder with image files, and a small bash script that creates an images.less/scss file with variable declarations such as $img-myicon: data:image/png;base64,.... I then use it like this: background-image: url($img-my-icon).

    Easy-peasy and no extra HTTP requests at all. Just remember to gzip your CSS.

  19. 43

    Gerd Wippich

    April 11, 2012 1:23 pm

    Someone deleted some of the links from the posts above (#3, #7, #11) – why? There are a lot of little helpers on the web I still don’t know, and now I never will… :-(

  20. 44

    There’s also It takes all your single graphics files and builds the sprite as well as the respective CSS-markup. Also SASS if you like.


  21. 45

    Its really nice collection.Thank you.

  22. 46

    Excellent idea to target specific squares within the sprite! I’ll definitely implement it.
    However, you lost me at LESS & SASS. I started reading and thought I would understand the core of the article, half way through i realized it was all about LESS & SASS.
    It’s tagged as “CSS” and “Essentials”. I disagree with the second one.
    It should at least be in title of the article.

  23. 47

    I created a CSS sprites generator aimed at area minimization using VLSI floorplanning algorithm.
    Have a try.

  24. 49

    I’m always using sprites but I’ve never really found it to be a problem except when I’ll occasionally reposition things within the sprite to make things a bit tidier.

  25. 50

    Great Article

  26. 51

    With CSS3 becoming more usable in the web design world, is there still a need to use SASS and LESS? I played around with SASS and LESS a few times in some temp projects and loved them, but is it wise to still use them with CSS3 on the go? What about using SASS and/or LESS on larger websites (100 – 150 pages)?

    • 52

      Writing CSS3 rules is one of the main reasons you would use LESS or SASS because using mixins it can automatically create all the extra lines with vendor prefixes for you.

  27. 53

    Mark W. Jarrell

    April 12, 2012 5:45 am

    I like using SpriteRight. It’s a really easy mac app that builds sprite images and CSS for you.

  28. 54

    I use my own method:

    <span class="ai-gfx ai-gfx-45">
    <img style="left:-45px; top:0"
    alt="Über Facebook kontaktieren"/>

    CSS: {
    overflow: hidden;
    display: inline-block;
    position: relative;
    } {
    width: 45px;
    height: 45px;
    } img {
    position: absolute;

    If you know CSS, you know what I mean.

    I wrap an inline-block element around a semantic correct img-tag. Then I position the img itself with inline css.
    – no semantic issues
    – image not as background, which is important for accessibility
    – option for background texture in the outline element
    – cleaner code (no selectors for each sprite)

    There’s an entry on my blog (still work in progress ;)):

    • 55

      Your solution is to use inline-css?

      • 56

        yes, for the coordinates of the sprite. And I have a good reason for that. There’s a direct connection between the img-tag and the result. I don’t have to search in the css file for coordinates. And I don’t produce such amount of code in my css file.

        Of course, you could make selectors for every image. Even in my solution. But I don’t think that’s the best way.

        There are other variations. You can make a matrix with your buttons on the y-axis and with the states them on the x-axis. Now, just add an img:hover rule with “left:XXpx” in your css et voila, you have hover states in the same image file.

        • 57

          Disable CSS.

          Look at the page.

          Now look at me.

          Look at the page again.

          Look at me.

          I’m on a horse (and you have images that break the content flow).

  29. 58

    Frank Villa-Abrille

    April 12, 2012 6:53 am

    I can’t believe you missed SmartSprites: CSS Sprite Generation Done Right, This eliminates the need to manually update your sprites via Photoshop and CSS. SmartSprites allows you to generate your and create your sprites automatically – meaning you can continue to create and maintain your images individually.

    “SmartSprites will let you easily introduce and maintain CSS sprites in your designs. SmartSprites parses special directives you can insert into your original CSS to mark individual images to be turned into sprites. It then builds sprite images from the collected images and automatically inserts the required CSS properties into your style sheet, so that the sprites are used instead of the individual images.”

    “In other words, no tedious copying & pasting to your CSS when adding, removing or changing sprited images. Just work with your CSS and original images as usual and have SmartSprites automatically transform them to the sprite-powered version when necessary.”

  30. 59

    I believe CSS sprites have not caught on due to overwhelming % of web developers DO NOT create their own images.

    • 60

      I reckon sprites haven’t caught on because many people don’t understand that the number of requests on a web page is a big problem…

  31. 61

    Easily Generate your sprite from Adobe Fireworks:
    Set up graphics in place (If you are using ‘print software’ such as Photoshop or illustrator, you can import your lay-outed and arranged sprite image as one file), set up slices in fireworks according to your desired positions. Save file.
    Download: and extend fireworks.
    Open file, run installed command (commands->export) ‘Slices as CSS Sprite’
    Open exported css file or copy and paste to your generated css
    Export image file in place
    Need changes in sprite? well if you used Fireworks for creating the original images – just add /change / rearrange the graphics and hit the export command again… Another win ;)

  32. 62

    Hi all,

    my big problem is that you want developers/designers to be developing and designing not optimizing. Let’s face it CSS sprites and inlining images is just the tip of the optimizing iceburg, and as we have seen these are time-consuming enough!

    My company has a product (Stingray Aptimizer) that auto-magically optimizes content using these techniques (and a multitude of others), so you don’t have to. Plus it keeps on optimizing even when the content changes etc.

    sign up for a free eval and take a look

    At present this is an IIS/SharePoint focused product (Microsoft is a reference here!), the next release will allow us to optimize all web content irrespective of the web server it is being served from.


  33. 63

    Jorge Bastida

    April 13, 2012 4:17 am

    Hey guys,
    Glue is a simple command line tool to generate CSS sprites, probably somebody will find this quite useful :D


  34. 64

    Flávio Araújo

    April 13, 2012 10:45 am

    My “secret” to work with css sprites is Fireworks.

    I use to make a copy of my image file and import/open on fireworks. Then I use to create slices on fireworks (what I think it´s much better then photoshop to do this task).

    So, fireworks at the botton of the workspace have nice X Y Width Heigth tool.

    So clicking on each slice, i have the perfect XY/ X Y Width Heigth values to use om my CSS file.

    I Think this is (as far as I know) the best way to do this boring task.

    • 65

      Michael Connors

      April 17, 2012 7:36 am

      Agreed—Fireworks is the way to go. It solves most dimensioning/slicing issues. Anyone struggling with these should look to Fireworks!

  35. 66

    Mark Simchock

    April 16, 2012 6:28 am

    For anyone who might be interested I threw together a proof of concept for responsive sprites:

    Naturally, I welcome any input, etc. There a couple limitations vs traditional sprites. But as mentioned it’s a proof of concept and the idea is still being developed.

  36. 67

    You may also like this technique using SVG in place of CSS sprites

  37. 68


    This site write for you the code to place the images of your sprite.

  38. 69

    Vignesh Nandha Kumar

    April 23, 2012 5:21 am

    I use a tool called *Spritemapper* and I wrote a wrapper script around to automate the process. So everytime I want to create a sprite, I simply put all the individual images in a separate folder and specify the folder name to the script. The script takes care of creating the sprite, even compressing it using trimage (a combination of optipng, pngcrush, advpng and jpegoptim) and generating the correspnding CSS. Once the script finishes, I just copy paste the generated CSS to my actual CSS file. Cool huh? You can get the script at

    Happy designing!

  39. 70

    I usually create my sites using individual images in dev mode, then when i’m just about ready to deploy to the server to go live I take all my individual images and drop them into spritepad from wearkiss ( and make my CSS adjustments to suit.

    It may take about another half hour to make all the adjustments, but it sure beats the Photoshop > HTML editor round tripping.

  40. 71

    The new upcoming Fireworks CS6 will have the ability to export sprites images and CSS codes in various layouts.

    You can do this by using slices on objects and states as well. It saved you a lot of time to prepare the images. It will auto rearrange the images to save the extra space in between.

    The ability to work on a design and do CSS sprites any time is just amazing. This will change people to do CSS sprites.

    Watch Fireworks CS6 features!/watch/cs6-creative-cloud-feature-tour-for-web/introduction-to-fireworks-cs6/

  41. 72

    Gustaff Weldon

    May 6, 2012 4:30 am

    Just wondering, why noone mentioned that sprites in :after and :before will leave the <IE7 without icons but with text-indent applied. This should be mentioned in the samples as people often tend to just copy and paste code examples without consideration. What happened to progressive enhancement, I can't recall hearing IE7 is no longer relevant…

  42. 73

    David Nemes

    May 10, 2012 2:14 am

    Using sprites is easy and fun, just use . It’s a sprite generator.

  43. 74

    I simply use SpriteRight, a Mac desktop store app that enables you to simply import an image, set any desired padding(if applicable), and when you export, it generates code that you can simply cut and paste into your web code (the only thing I found I had to do is adjust the path with the background URL to ensure it points to the proper directory where the sprite sheet is located on your server.

    No fussing around with coordinates and calculations. once I tried out SpriteRight, I don’t see the need for anything else IMO (of course, this is all subjective and a matter of personal taste and work flow preferences).


  44. 75

    There is a tool to find CSS sprite x and y coordinates

    • 76

      For some reason I feel easy to use than sprite cow and it also works in IE (not a big deal though :) )

  45. 77

    Jorge Vargas

    July 10, 2012 11:15 am

    The best css position automatic

  46. 78

    Lucian Adamson

    July 23, 2012 6:59 am

    For the users getting the “undefined” error relating to the guides.add portion of the Adobe Photoshop grid script:

    The script in question will only work for Adobe Photoshop CS5+

    Bah.. so unfortunately those who are under CS5 are out of luck. Including me. :(

  47. 79

    Hey! If your site is using php, then the math for the icons can easily be calculated and the coordinates echoed into resp. inline css…
    In a grid that’s super easy. In “wild” sprite it’s also easily done.

    The only thing you need is the sprite image, and if you change it just change the php code. In this manner you can easily manage several sprites.
    That is, let php pick up the sprite you’ll use for the moment…

    Sara, a smart eady going lady of Sweden

  48. 80

    The links to RSS, Facebook, Twitter, Newsletter in the top right corner of this page are empty when images are disabled. Concerning accessibility: Wouldn’t it be better to use regular images for these links?

  49. 81
  50. 82


    November 21, 2013 11:28 am

    I feel stupid to ask this question but I have to do it: how is it possible to add text-number into working area?
    “Finally, to really finish things off, you can add numbers to the x and y axes of your grid so that you can easily pinpoint every square in the grid. Don’t add these numbers to the actual sprite, though; just copy the sprite into a new image and add them there. These numbers are just for reference—but trust me, they will definitely come in handy in a minute.”

  51. 83

    sad that nobody mentions photoshop’s scripting abilities.
    just search for: css sprite javascript photoshop
    and you will find lots of export scripts that do the job.

  52. 84

    I always ask others to read through this excellent post on CSS Sprites. I have even mentioned it on my website blog. We learn from your website.

  53. 85

    Osman Fikret Ceylan

    December 15, 2014 1:11 pm

    If someone needs to convert image to CSS codes, xml or data uri and also needs to create CSS sprite as retina or standart options these links can help them:

    Base64 CSS Generator
    Online base64 css, dataURI generator. Convert your images easily to base64 CSS, Data URI, XML.

    Retina CSS Sprite Generator
    Generate retina and standard sprite images online with diagonal, left-right, top-down algorithms. Get your retina ready CSS codes instantly.


↑ Back to top