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 Death311. 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 website2, many high profile websites implement the technique, including Google and Amazon. There are numerous tutorials3 which help you get to grips with the techniques and sprite generators4 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”5. 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 clouds6.

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 example22, 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 TwinHelix28 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:

Footnotes

  1. 1 http://www.alistapart.com/articles/sprites
  2. 2 http://developer.yahoo.com/performance/
  3. 3 http://www.smashingmagazine.com/2009/04/27/the-mystery-of-css-sprites-techniques-tools-and-tutorials/
  4. 4 http://spritegen.website-performance.org/
  5. 5 http://blog.vlad1.com/2009/06/22/to-sprite-or-not-to-sprite/
  6. 6 http://www.neogaf.com/forum/showpost.php?p=9490699&postcount=70
  7. 7 ?hex=000000
  8. 8 ?hex=c4c4c4
  9. 9 ?hex=ea1d22
  10. 10 ?hex=309721
  11. 11 ?hex=005aa9
  12. 12 #
  13. 13 #
  14. 14 #
  15. 15 #
  16. 16 #
  17. 17 ?hex=000000
  18. 18 ?hex=c4c4c4
  19. 19 ?hex=ea1d22
  20. 20 ?hex=309721
  21. 21 ?hex=005aa9
  22. 22 http://www.smashingmagazine.com/wp-content/uploads/2010/01/transparent-sprite-fonts.png
  23. 23 #
  24. 24 #
  25. 25 #
  26. 26 #
  27. 27 #
  28. 28 http://www.twinhelix.com/css/iepngfix/
  29. 29 http://wellstyled.com/css-nopreload-rollovers.html
  30. 30 http://spriteme.org/
  31. 31 http://www.alistapart.com/articles/sprites
  32. 32 http://developer.yahoo.com/performance/
  33. 33 http://spritegen.website-performance.org/
  34. 34 http://blog.vlad1.com/2009/06/22/to-sprite-or-not-to-sprite/

↑ Back to top Tweet itShare on Facebook

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.

Advertising
  1. 1

    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
  2. 52

    Giacomo Colddesign

    November 2, 2010 1:26 am

    Really interesting.. thanks!

    0
  3. 103

    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
  4. 154

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

    1
  5. 205

    Old stuff sold as new

    1
  6. 256

    Agreed.

    0
  7. 307

    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
  8. 358

    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
  9. 409

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

    0
  10. 460

    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
  11. 511

    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
  12. 562

    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
  13. 613

    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
  14. 664

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

    0
  15. 715

    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

↑ Back to top