Transparent CSS Sprites

Advertisement

One of the most useful front-end development techniques of recent years is the humble “CSS Sprites”. The technique was popularised by Dave Shea on A List Apart in 2004 with his article CSS Sprites: Image Slicing’s Kiss of Death. CSS Sprites are a relatively simple technique once you understand the fundamentals and it can be applied in all manner of ways. A common use is for a graphic intensive navigation, but it can also be useful for buttons or even styling headings with the corporate font.

Sprites are simply a collection of images which are merged together to create a single file. You then use CSS, changing the background-position the image, to display the correct part of the image you need. I often use the analogy of a large object passing a window — you only see what is within the frame.

Over the last couple of years CSS Sprites has been one of the most widely adopted CSS-related techniques. Popularised by the Yahoo’s research and documentation around speeding up your website, many high profile websites implement the technique, including Google and Amazon. There are numerous tutorials which help you get to grips with the techniques and sprite generators which help you create the graphics themselves.

The Benefits and Potential Problems

CSS Sprites have become a de-facto way of improving the speed of your website or web application. Merging multiple images in to a single file can quickly reduce the number of HTTP requests needed on a typical website. Most browsers only allow for two concurrent connections to a single domain so although individual files can be large, the overall request and response times are considerably lower. Combining images with similar hues also means the colour and compression information is only need once, instead of per file, which can mean an overall reduced file size when compared to the files individually.

The benefits of reduced file size and HTTP requests are often publicised, but potential problems are rarely ever discussed. One of the main techinical issues with CSS Sprites is memory usage which is explained in the article “To Sprite Or Not To Sprite”. Another issue is the maintenance of the sprites, the images and the CSS, both of which can become rather complicated.

A Technological Solution

A common practice in solving slow-down in computing seems to simply throw in more hardware. We all know hardware prices are dropping all the time, so this seems like a reasonable solution. However, I feel there is a fundamental flaw with this philosophy and ingrained mentality. Developers have access to more computing power and as such they code their applications to be handled in these environments. With each new feature the application becomes slower and slower, but this problem has already has a solution — upgrade your hardware. This is an endless cycle.

Many of the user interfaces people come across today are on the Web. This means the user has to download most of the related material (images, CSS, JavaScript) before interacting with the content, so the same philosophy must be applied to the Web. Websites, or more recently web applications, are becoming more complex, even replacing many desktop applications, therefore the user must first download more and more information before beginning their experience.

Although file sizes required to view a website have increased dramatically over recent years, more and more people are upgrading their Internet connections, with broadband becoming the norm in many countries. This cycle conforms to the hardware upgrade philosophy and in theory should negate any potential user experience problems.

However, web developers are falling in to the same trap which many application developers have before. As layouts become more complex, more images are required and so the developer creates more images — even if they are sprites. This seems like a reasonable assertion, but it doesn’t mean it is the best solution.

A Twist on the Technique

Due to the limitations of the Web, there have been many inventive solutions to problems. But the Web isn’t the only place where there can be very tight limitations. Innovation strives on limitation. A great example of this was in the iconic game Super Mario Brothers where the bushes were just recoloured clouds.

This very simple but extremely effective implementation made me think about how to reuse common interface elements, trick the user to believe something the same is different!

Now on to the twist, this idea is to create a transparent sprite allowing the background-color to show through. If you are familiar with CSS Sprites, you should be able to grasp this twist relatively easily.

Simply, an image with a transparent “knocked-out” transparent center is placed over a background colour. Changing the background colour changes the appearance of the element. The only thing you need to pay attention to is that the colour surrounding the transparent part of the image matches the background in which you are using the techinque. This stops the background colour bleeding in to other parts of your image.

Anyway, this technique is much easier to understand in an example…

Example

The following example is only made up of three images. One for all the font samples, one image for both sets of droplets, including hover and active states, and one for the all buttons.

The Images

Fonts
The font image contains transparent typefaces on a white background, meaning they aren’t viewable on a white background. Save the file from the example, open it in your favourite graphics editor and you will see the transparent typefaces.

Drops
The drops image is used on the example above as the colour picker. A single graphic containing the gradient drop on the two different backgrounds, so the background-color is masked out correctly. The image contains all three states used in modern interactive interfaces — static, hover/focus, pressed/active.

Button
The button technique is the most flexible and probably most useful way to use this technique. A simple sprite image containing two states — static and hover/focus — which is then placed over text to create the button. Simply adding a background-color will make every use of this button the same style across your application or website.

Below is some CSS which styles simple fixed width buttons with a grey background colour, but also has two different treatments, “warning” and “go”, which have red and green background colours respectively.

a.button {
  display: block;
  width: 80px; height: 30px;
  margin: 0 20px;
  font-size: 14px; line-height: 30px; color: #fff;
  text-align: center; text-decoration: none;
  background: #4a4a4a url(button.png) no-repeat 0 0;
}
a.button:hover,
a.button:focus,
a.button:active {
  background-position: 0 -40px;
}
a.button.warning {
  background-color: #ea1d22;
}
a.button.go {
  background-color: #309721;
}

The CSS above produces the following buttons:

Conclusion

This techinque could be useful when providing a range of themes for a website. You could create one set of buttons and icons then add the background colour which best suits the selected theme.

Although this technique will never be as broadly useful as the original CSS Sprites, the idea can be useful for websites which allow user theming. The technique could also be used when creating HTML mockups, allowing you to easily update colours based on client feedback.

The main benefit this technique has is that it reduces the number of HTTP requests. But it also reduces browser memory usage compared with what would be needed if you created a larger sprite to handle all the colours you need.

I would like to mention one caveat though, IE6, because it does not natively support transparent PNGs. There are PNG fixes, but none1 of these support background-position which is needed if you are using this technique with CSS sprites, such as with the buttons and droplets above. However, you could provide a slightly less optimal experience using GIFs instead.

1. The IE PNG Fix from TwinHelix does include support for background-position, but the solution requires JavaScript.

Further Resources

If you are interested in any aspect of CSS Sprites, check out the following extra resources.

Below are a list of links used within the article:

↑ Back to top

Trevor Morris a twenty-something web developer based in the Midlands, UK. He is fluent in both front- and back-end coding, and develops usable and accessible front-end interfaces using web standards. He is freelancing at Surface, occasionally writing about the web and always rating movies on his personal site trovster.com but for more up to date commentary you can follow him on Twitter. He is also a prominent member of the The Multipack, a community of multi-talented Web professionals from across the West Midlands, where he helps to organise the “Presents” talks and the free yearly event Geek in the Park.

  1. 1

    Good article and interesting technique. Alas, I try to stay away from PNG’s simply because of IE6.

    -39
  2. 2

    In your article you say

    “Most browsers only allow for two concurrent connections to a single domain”

    This may have been true in 2004, but isn’t anymore. See for example Steve Souder’s »Roundup on Parallel Connections« from March 2008:
    http://www.stevesouders.com/blog/2008/03/20/roundup-on-parallel-connections

    3
  3. 3

    With DD_belatedPNG you are safe using transparent PNGs in IE6 :)

    3
  4. 4

    My website uses this technique as key design element (+ mixes it with color transitions).

    5
  5. 5

    @Adam: IE6 users are by now used to websites simply not working for them, or in the best case looking “corrupted”. Unless a client specifically demands a layout that is optimized for IE6, I feel that non-transparent PNGs are a trivial problem for IE6 users. Even on our government website (aimed at non computer-literate minorities) IE6 use is as low as 3%!

    21
  6. 6

    Yesx this is a great technique to use. I create scalable web apps that can be branded to different colors depending on the client, and this technique makes it so I don’t have to change the icons with each color change, just adjust 1 line of CSS.

    1
  7. 7

    @adam the IE6 PNGfix doesn’t take long to install at all.

    -2
  8. 8

    Cool technique! The single image droplet alone was worth the post. Thanks for sharing.

    0
  9. 9

    I prefer not to use images for layout style if I can, but this could be a great idea, particularly, as you said, for interchangeable themes. Seems to give the designer more power, even if they only ever used it in a testing environment.

    Thanks for the article!

    0
  10. 10

    this is nothing new

    -1
  11. 11

    Thanks for css sprite generator. I thought spriteme was the only tool out there until now.

    0
  12. 12

    I may need to read this again. I’ve used either id and id:hover with background urls and negative margins or the classic sprite technique with bg position but always with PNGs, which I make transparent. How is this new then?

    Like I said, what do I know, I have to instapaper this and come back ;)

    0
  13. 13

    The image from your link to the super Mario game has gone. You can still find it in Google though.

    0
  14. 14

    We have thought about this technique a few months ago for our website, to create themes to suit the customer’s colors. But a lot of our website’s visitors have to suffer corporate policies, which require the unfortunate use of IE6 (it’s still 20%)

    So this wouldn’t work, It is a great technique though, but everthing will be more or less monochromatic, you can use everything from white to black and a color.

    2
  15. 15

    I use this a lot of my interface such as buttons. It’s just a gradient but with no color so you can easily specify it in the CSS.

    0
  16. 16

    We used to use the same technique with transparent GIF’s back in 2001 on a site that used white backgrounds to give us rounded corners on boxes of different color.

    I.e. the gif would be divided into two by a curve on it that was half-white, half-transparent – one image per corner. These four little images would let us get aliased curves for a all corners of a box of any colour providing it was sitting on a white background.

    [)amien

    0
  17. 17

    I’ve used sprites on a movie trivia site I’ve been working on (bitplay.net). Rather than transparency though, I’d rather have animated gif sprites. Haven’t really figured out a good way to put those together. Would be very useful.

    0
  18. 18

    Never really thought of using sprites that way.
    I always had 3-4 variations of the same image within the sprite.
    I guess this is shaving a little more off this size of the file
    - will give it a try on next calling for a sprite

    Cheers

    0
  19. 19

    I appreciate the effort to write the article, and doubtless it is intended for “the next generation” of web designers / developers i.e. those just really getting started with “advanced” (it’s a relative term) CSS techniques.

    That said, I’m always a bit disappointed when I see an article like this, which is really just rehashing well-documented techniques without giving due attribution to the true pioneers and though-leaders in our industry who originally forged these techniques two to five years ago (or longer).

    Granted, you mention Dave Shea and his landmark article on CSS Sprites – from waaaay back in 2004. But indeed the basic transparency concepts discussed in this smashingmagazine article have been verbosely covered elsewhere already… by the folks who forged them.

    To wit:
    * http://simplebits.com/notebook/2003/07/24/magic-icons-for-lazy-people-like-me/
    * http://www.digital-web.com/articles/web_standards_creativity_png/
    * damn, even SmashingMagazine itself in 2008: http://www.smashingmagazine.com/2008/04/16/getting-creative-with-transparency-in-web-design/

    Yes, this latest article takes those ideas and adds a “twist”… sorta. And hey, like I said it’s great to introduce the concepts to folks who aren’t yet familiar with them.

    Just give credit where credit is due. We are standing on the shoulders of giants. Proper attribution is the least we can do.

    6
  20. 20

    Good article.
    SM always gives good articles, but i am a little disappointed to always find that “off topic’ thing in every post. I think SM is extremely popular and they do not need these spam (not intended to be offensive) kinda things. While there is an ad that informs about a particular thing, why do you need to make a great article look not so great. Again, this is just a suggestion. Good things will always get buyers.

    I love SM. :)

    0
  21. 21

    I used this technique several years ago using the twin helix fix, for a online learning management system.

    What we incorporated was a fallback for ie6 to our default color scheme.

    We removed full support for ie6 from our supported browser list (and schools are about as backward as it gets) and offered functional support for ie6.

    0
  22. 22

    I’m not techie enough to say which fix is ‘the best’ but I’ve had very good luck with http://www.dillerdesign.com/experiment/DD_belatedPNG/ as a .PNG background image IE6 fix.

    0
  23. 23

    Where is the calendar for this month ??

    -10
  24. 24

    What about Data URLs in your CSS? I’m not really into that yet but it seems like an interesting alternative to sprites.
    http://www.websiteoptimization.com/speed/tweak/inline-images/

    0
  25. 25

    Its very old technique. Whatz new tried here? Im not impressed.

    -4
  26. 26

    I personally think this is a nice technique. Some time ago I used something very much alike on a project we’ve been working on. I noticed we’d need many coloured buttons and as such introduced the said technique. @Omprakash: Even though this technique may have been around for a while it doesn’t hurt to enlighten it again. As you can read in the comments it’s also a much appreciated article.

    0
  27. 27

    If you want IE6 to fallback without any additonal CSS / JS or images then you should use an 8-bit PNG for the gradient. With PNG8, IE6 will make any alpha pixels completely transparent so you’ll end up with a solid background colour rather than a gradient.

    But, if your a foward looking developer then you should really be using CSS gradients for this type of thing.

    0
  28. 28

    I use Chrome Frame to fix the blue the pngs add to IE6. It works even if javascript is turned off.

    0
  29. 29

    This technique is used on Aflac.com in the secondary navigation (in the white bar under the tabs), and in the global navigation in the upper-right corner. It’s a quite versatile technique that allows the creation of new navigation items without having to create 3 separate images (default, hover, current). Plus, if you change the color scheme, all you have to do is change the hex values in one place instead of re-creating all of those images 3 times.

    0
  30. 30

    the real reason for using sprites is eliminating the lag before loading the hover/active image. When you got bigger images the lag could be a real pain and would make it really user-unfriendly.

    Take a look e.g. at the image menu with 4 products on http://www.aquamarinespa.cz/ and try to hover – I needed transparent background and full colors, so i was pushed to use PNG, so if i would create each button separately and for standard/hover, they would have about 30 kB. And bet that you would notice the lag for hover, especialy when you would download other things, e.g. other images on the gallery on this page.

    So I have created one http://www.aquamarinespa.cz/wp-content/themes/aquamarinespa/images/bg-intro-produkty+hover.png file and it is smaller then 8× small image and with no lags.

    0
  31. 31

    very beautiful.thanks for sharing

    0
  32. 32

    I use this technique in my error pages to add a little color fader to the logo when you hover over it, just for fun. Example here http://blobbr.com/404 and the demo it was based on here http://blobbr.com/demo/mask.html

    0
  33. 33

    Great read. Damn IE 6 at it’s lack of PNG support….

    0
  34. 34

    Very nice technique, I think this might come in really handy when you’re creating an app or widget. By a change of the background-color you can pick you’re own style.
    Downside of all this might be to lose the scaling ability of the elements.

    0
  35. 35

    Giacomo Colddesign

    November 2, 2010 1:26 am

    Really interesting.. thanks!

    0
  36. 36

    Old stuff sold as new

    1
  37. 37

    I think a lot of owners/ceo’s are just intimidated by the ever-changing world of browsers and technology in general. I know I have trouble keeping up with all the choices and sometimes I’m not sure where to begin.

    0
  38. 38

    No doubt it is good feature, I have seen it long time ago on any other website. button looks great, but as much i know, colored button is not considered a good idea in larger websites.

    0
  39. 39

    Great read. This technique is under-utilized in my opinion. It’s especially great for building CMS templates (e.g. WordPress) which allow non-technical users to control the color scheme.

    As for IE6, I think generally speaking it’s better for everyone if the user experience on that browser is noticeably inferior. It will drive non-web folks to demand upgrades sooner. We charge by the hour to make sites IE6 compatible – all other major browsers are free.

    0
  40. 40

    I wrote an article for designers about using CSS sprites a while back:

    http://fringefocus.com/2010/tutorial/css-sprites-theyre-awesome-use-them

    I, for one, absolutely love using sprites as a solution. They’re often a lot faster than other methods, and easy to make broad design changes with.

    0
  41. 41

    I love the IE6 debate above. Personally I think everybody should continue to support IE6, just like smashing magazine does….uhhh….wait a second…. ;)

    (for those of you who are unfamiliar with sarcasm, check this page in IE6)

    0
  42. 42

    Awesome trick!! keep em coming and f**k IE6

    0
  43. 43

    Transparent images are not yet a CSS standard, yet they are supported by most modern browsers. However, this is part of the W3C CSS3 recommendation. Implementation varies from one client to another, so you will have to use more than one syntax for cross-browser compatibility.

    http://www.handycss.com/effects/transparent-image-in-css/

    0
  44. 44

    You don’t have to try stay away for the IE6 png problems there are a lot of solutions available on the internet to tacke that problem.
    Take for example:
    http://www.komodomedia.com/blog/2007/11/css-png-image-fix-for-ie/

    9
  45. 45

    IE6 PNGFIX is a great way to use png in your projects when you want it to be IE6 compliant. Png’s without the alpha channel you can use without the pngfix sollution.

    http://jquery.andreaseberhard.de/pngFix/

    -2
  46. 46

    IE 6? Who cares about IE 6. Force your users to upgrade and stop encouraging them to use of an outdated browser with security vulnerabilities. Come on man. IE 9 is about to be released and you’re still try to support IE 6? Take a clue from google.

    30
  47. 47

    Bad habit, IE6 is dead and shouldn’t receive any attention anymore …
    The faster webdesigners left out this obsolete browser, the faster he will be gone.

    1
  48. 48

    I believe what Adam is trying to say is that pngfixes are all just workarounds, and it’s better from a cross-browser compatibility standpoint to use transparent gifs and other formats that work well with IE6 rather than a workaround just for IE6.

    1
  49. 49

    im surprised this top comment has so many thumbs down. its the best comment here. IE6 compliance is sadly pretty vital, and at least some info on degradation and hacks should be in the article. i for one don’t use PNGs for this reason

    Thumbs up all!

    0
  50. 50

    The IE6 PNG fixes don’t let you position the background image so CSS sprites don’t work in that situation

    7
  51. 51

    Indeed. It’s presented as an innovation or other new stuff, but I used it before and I have seen it on other websites a long time ago.

    2
  52. 52

    It’s hard to force most corporations to upgrade their web browser. My wife works for a very large international company, they all still use IE6.

    8
  53. 53

    Not much I can do when for example a client that sells services to hospitals requires it because of the number of out dated intranets that run on IE6.

    I think I should have mentioned I am aware of all the PNG fixes, but I’ve had issues with them being buggy and thats why I usually avoid them. That’s all.

    6
  54. 54

    My sentiments EXACTLY.

    I’m so sick and tired of supporting that pitiful excuse of a browser (IE6) And when I hear Microsoft is CONTINUING to add proprietary crap into IE9, there simply is no excuse they can give that would disprove that they are not about advancing and standardizing the web.

    I have no qualms losing whatever business I do because I don’t support that pitiful archaic browser.

    0
  55. 55

    Peter –
    I agree. At this point, designing for IE6 (using an IE6-specific stylesheet) should be limited to making the sure the needed information is clearly available. Don’t cripple good design for current browsers by forcing IE6′s limitations on it! And I say this as someone who still uses IE6 on one home machine.

    P.S. – I meant to vote your comment up, but clicked the thumbs-down icon by mistake. Please add 2 to your thumbs-up score.

    8
  56. 56

    Of course we all know that isn’t true. The majority of IE6 users aren’t so by choice, but cannot upgrade their software. Ignoring their needs will not accelerate the browser’s decline.

    That said, I’ve used this technique on a few sites, and I’ve have not found it very difficult to just remove the PNG24 sprite and implement other appropriate styles in a IE6 stylesheet.

    2
  57. 57

    I haven’t used it in a while as we no longer have to support IE6, but I’m pretty sure DD_belatedPNG (http://www.dillerdesign.com/experiment/DD_belatedPNG/) allows for using sprites and background-position..much better than IE PNG Fix (http://www.twinhelix.com/css/iepngfix/) anyway….

    6
  58. 58

    Drew Diller’s PNG fix does indeed allow background-position. It really is the only PNG fix you should ever use.

    http://www.dillerdesign.com/experiment/DD_belatedPNG/

    3
  59. 59

    Agreed this article is totally a rehash of a well documented technique and it’s doesn’t even do a great job of it.

    The article lacks substance and depth. And although I usually complain about the showcases here, this particular article lacks even more depth!

    Fine, if you are gearing the article towards the next generation of developers, but a fixed with button is really lame example. Take it one step further and show the kids how to do a sliding door button and maybe then I wouldn’t bother to write this negative critique.

    And while we’re at it, most seasoned front end developers are shying away from spriting buttons anyway. CSS3 will make that obsolete. You can do it well enough using just CSS and providing a normal repeating gradient background to satisfy IE (although you lose the corners).

    Anyway, a much more useful spriting technique would be to sprite button icons and to add an icon to the button (e.g. ‘+’ for add, arrow for continue, etc.) by just adding a class or two to a button and having the width expand accordingly.

    Another thing I’ve actually done for work is to sprite carousel slideshows on high traffic homepages. Far fewer request calls and sometimes you can even bring the overall filesize, for example, of 10+ images or so from 140k to 100k, nearly 30% decrease, which is huge on a high traffic site.

    Anyway, looks like smashing is have a slow holiday weekend.

    0
  60. 60

    Agreed.

    0
  61. 61

    IE6 is rubbish agreed, however, many businesses and organisations are stuck with it for various reasons including business critical applications that rely on IE6 for them to operate correctly.

    As designers and developers it is our job to communicate information in the best possible way, from both an aesthetic and development standpoint.

    If you know you’re likely to received a lot of IE6 visitors it’s your responsibility to build a reasonable experience for all visitors as well as educate them to make informed decisions such a browser use. The same also applies to accessibility issues for those visitors have have visual impairment.

    Who are we as designers and developers to decide that one group of users should be dropped, just because it’s a pain to develop for their browser? How does that add value to the web or contribute in any way to a wider, open web experience?

    The majority of IE PNG fixes I’ve tried that use JavaScript are power hungry and take forever to load. If a user has IE6 9 times out of 10 they’ll have a slow PC too so using these fixes is largely pointless.

    The only real way of building a truly accessible site to all is graceful degradation and to realise not everyone will see your website in all its glory with all its bells and whistles but at least they have the best experience they can given the browser they have.

    13
  62. 62

    Antonio Ciccarone

    November 1, 2010 12:18 pm

    Yup, mine too – when I create applications I use a virtual PC to test in that god-awful POS. I hate ie6

    1
  63. 63

    I agree, I think the best way to combat PNG’s in IE6 is to simply replace them with an IE6 stylesheet.

    1
  64. 64

    I had to thumbs down this comment, just because of the “who are we to decide?” diatribe.

    I’m sorry, but to even espouse that idea is offensive to me at the most basic level. It so very contrary to what we as designers and developers are supposed to stand for.

    Our jobs, as designers, and developers, is to push society forward. New processes, new forms of beauty, new methods of being more efficient. At our core, we are all problem-solvers. To not push forward is to die a slow death.

    Were we to settle for IE6, we’d be tossing a few millennia of evolutionary progress to the side to say “eh, it’s good enough.”

    Imagine art today if man had been content to paint stick figures in blood on cave walls, instead of trying to improve. Imagine medicine in man had been content to treat diseases with leeches and other misguided concepts about the human body?

    If you showed up to your high school prom in jorts and a t-shirt, were you allowed in? No. Absolutely not.

    Our job is not to “create gracefully degrading sites” so that users can still access the content in a browser agnostic fashion. Our job is to leave those non-compliant users behind, because they are an anchor on our progress. Our job is to frustrate those who refuse to move along and progress into doing just that by denying them the content they need. We have a responsibility to ourselves and the others in our profession to be absolutely ruthless about it, as well.

    Our jobs do not exist to accommodate – they exist to innovate. We deal solely in progress, and to assert otherwise is inherently misguided.

    2
  65. 65

    It’s everyone opinion to share. @Ravi: Try to stick with your own comments.

    0

↑ Back to top