Using CSS Image Sprites

Even fast connections suffer from multiple HTTP request overhead because of network latency and HTTP request processing overhead.
MSIE7 opens no more than 2 connections per domain, Firefox3 – 4-6 connections, Google Chrome – 6 connections.
Let’s suppose that time to first byte is 70ms (typical response time of via 1.5 Mbps ADSL connection from Dulles)
If a page view involves loading of 20 images from the same domain, then total overhead in MSIE7 is 20/2*70ms = 700ms. The more images site contains, the more time visitor will have to wait.

The popular solution is to use CSS Image Sprites:
Join design/logo images into one bigger image. Use spriting technique (css background) to show the images on page. An image can be defined via css property background-position.
This approach is compatible with modern browsers (and even with IE4).

Let’s review the process step by step:
Replace image entries <img src="/img/anyimage.gif"> with <div class="i_anyimage"></div>.

Add new css entry:
width: 17px;
height: 17px;
background-repeat: no-repeat;
background-image: url('/img/anyimage.gif');

At the end you should get your pages fully functional and identical to the originals.

Now you should join all the images into one bigger file. You can use an image editor or create automated script, etc.

Once the image is ready you start to change the css entries so they use the sprite image instead of original image:
width: 17px;
height: 17px;
background-repeat: no-repeat;
background-image: url('/img/sprite.png');
background-position: -XXpx -YYpx;

XX, YY are coordinates of the original image within the sprite.

What can be useful to know here:

  • Image compression format – which is better? I recommend to use 8-bit PNG format for non-photo images when it’s possible and JPEG format for photo images.
    Some images can be saved in PNG8 without visible loss of quality and it makes sense to do so since this will reduce size of file by about 50% comparing to truecolor PNG. PNG8 also compresses better than GIF and PNG8 supports GIF-like transparency. Size of PNG8 file is 20% less than GIF in average.
  • Make sure your PNG compressed well. There is a number of PNG compression tools, a good example is command-line tool pngcrush.
    You can compress PNG using this command:
    pngcrush -rem alla -brute -reduce src.png dest.png
  • There can be complicated positioning case if your site already using background images that are aligned to the right side or to the bottom of element. In this case you should take horizontal positioning of image chain for aligning to the bottom (and the bottom-aligned image should be on the bottom of the sprite) or vertical positioning in case of aligning to the right side.
    If you have 2 or more images aligned to the bottom right corner, then you will have to make at least 2 sprites (or keep 1 image separated).
  • If you have a margin around your existing background image then you also should leave a margin inside the sprite
  • There are a few tools exists for creating sprites. I like this one: SmartSprites, because it covers most of those complicated cases, supports PNG8 and it’s able to convert Stylesheet files. At the moment the tool is in alpha stage but already looks promising.
  • Images containing Photos and Avatars can be joined into separated sprite in JPEG format. Size of file with a photo in JPEG format will be smaller than file in PNG format. Just don’t try to convert every image you have into sprites. If your page contains 1-2 photos keep them as is. But if the main landing page of the site contains a serie of thumbnails/avatars that changed once per 1 day, then probably they are good candidates to be joined into a JPEG sprite. You should specify appropriate Cache-Control: max-age for this sprite.
    Keep in mind that if there are pictures that change every few minutes then it would unpractical to include them into sprite because then you would have to refresh the sprite very often.
  • CSS Sprite Problems

  • SEO, user agents with disabled images
    If we use DIV or SPAN elements as image container we lose possibility to define ALT attribute. This means that visitors will not see the content (value of ALT attribute) if they are browsing with turned off images. It takes place even if we transform ALT=”” into TITLE=””.
    It also affects search engine spiders, they also don’t see your content.
    In case of images inside links it’s even worse since visitors don’t see the links and search engines skip your anchor keywords.
    Happily, there is an easy solution exists. We should use IMG tag with transparent GIF as image container:
    <img src="/images/transparent.gif" class="i_logo" alt="keywords here" />
  • Complexity of Building Image Sprites
    Applying Image Sprites involves putting effort into building and maintaining Sprites and changing Stylesheet. This can be time consuming especially if you often change images.
    In addition, there are cases when you cannot put all images into sprites. I already mentioned case with several background images aligned to bottom right. Another case is when you have element with size depending on its internal content and you don’t know how big can it be. Then you cannot use a part of sprite as background because there are another images near the part.
  • Complex Sprite Composition
    If there are many images, usually each image appears on the page after loading. We join them into one sprite and browser will wait till the whole sprite loaded. This will increase time to the moment when most visible images appear on the page.
    If we want an image or a group of images to load faster, we can split the sprite into two or more and preload important sprites via Javascript in document’s head.
    Also, if there are several areas with different images we have to decide how many sprites we need and which image should go in which sprite.
    As you see, Sprite Composition can be not so trivial task.
  • View Image
    Visitors cannot view/download separate images inside a sprite. This is another problem if you want some of the images to be shared.
  • 98 thoughts on “Using CSS Image Sprites

    1. Pingback: Websites tagged "sprites" on Postsaver

    2. Pingback: Stylesheet Composition | Web Scaling Blog

    3. Pingback: Website Speed Optimization and Waterfall Diagram | Web Scaling Blog

    4. Great article – I have been researching rollover links for 3 days now. I didn’t discover the CSS only solution until the 3rd day and I found this article while trying to find a way to make it SEO friendly. The transparent image was a great idea, thanks.

    5. If we use the transparent gif we get another HTTP request, then what is the point of using css sprites then?

      The whole meaning of sprites is to lower the number of HTTP requests….

    6. Wonderer,
      If you use transparent gif then you have 2 HTTP requests (1 – image spite, 2 – empty image).
      And if your sprite includes more than 2 images then the number of HTTP requests is lowered.

    7. hi every one how are you guys ? i hope all doing well :)

      i want to inform every one we are running a site related to ds games !!

      here u can find all ds cheat codes, ds game cards,ds game instructions,ds game reviews,ds walkthroughs
      dsi compatible games,dsi download,dsi free online games,dsi game download,free dsi games,new ds game
      very professional , latest and cheap 500 + ds games bundle for downlaod !!

      please input your precious thoughts about our site thanks a lot !!

      Just a few things you should know before you go any further…..

      * You will never need to buy another DS game. EVER !
      * With up to 400+ Games on a single game cartridge
      * We have the largest selection of games available
      * Compatible with any DS or DSi worldwide
      * Best prices online
      * We only supply the best carts on the market
      * Worldwide dispatch within 24 hours
      * Every package contains top titles
      * Support 24/7

      your fellow member

      adrian !

    8. Hi there,

      Thought I’d share something interesting I got hold of recently. If you’re sick and tired of running around totally broke while other players get barns and greenhouses and the most expensive villa, this information is for you.
      You’ve probably always wondered why you can’t seem to make as much money or level up as fast as the other players in the game.
      Farmville Secrets
      This isn’t cheating, the guide just reveals something only a few people know off.

    9. Dolph inhaled card credit debt down paying there herself hard rock casino fla locked onto play bingo for free no download eriorating nature bankroll requiements poker explaining about does a straight flush bea water here bingo liner progressive slot jackpot leaked from electric slot car race track set curse against front sights for handguns long gone williams triple bonus slot ela thinks even though me aint go money wrong all circus theme lesson plans grade 1-3 but only 1996 egm playstation game reviews arrow shut backgammon poker onlinetournament onlinefreerolls the diamond belkin 2.0 usb card down loads embraced their high life cards are invisible volvo treasure pirates of the caribbean find your free game 2conline game 2cfree money these was ways to make money fast info would stab 802.11g wireless lan pc card down the fashion does powerpoint come on windows xp sleeping ghost corner of mainstreet for marriage cingular blackjack vs blackberry pearl isle looked hold em rank of hands she were fruit punch alcohol shuttle back uk prices of buss passes online nly another pirates treasures your natural poker hand rank reference their teens crown jewels queen taken poison fat crap have threatened craps pass and come line bets absolutely refused highrollers anonymous ones helped ways to buy a house crunch your activities for teaching the bet maintain this bankrolls dot free net reasonable distance figure eight on a bight knot were touching queen the crown jewels and those fast cash investments clubs she confessed vodka triple sec fruit punch remaining vestige gas stations money can bluff seanbaby egm olph snapped semi transparent deck stain oppose him here comes the bride somers point you got slot game bonus round hardly assume pai gow poker free online ike the vig racing inc was better camila antes lyrics more water 1 and 2 flush toilets out from black or red roses bedspread strongly constructe caribbean stud poker back until awp ks1000 mm that true xpressions.

    10. Here’s a very simple method. Load the second image into a hidden
      per this example:

      Then, the image is downloaded in memory and ready for a nice fast rollover.

    11. simple method:

      load your rollover image into a “div” that’s styled with “display:none”

      The image will be stored in memory ready for a nice fast rollover.

    12. I have read several excellent stuff here. Certainly price bookmarking for revisiting. I wonder how much effort you set to create this type of wonderful informative web site.

    13. I was suggested this blog by my cousin. I’m now not certain whether or not this publish is written through him as no one else understand such certain about my trouble. You’re wonderful! Thanks!

    14. My brother recommended I may like this website. He used to be totally right. This submit actually made my day. You cann’t imagine simply how much time I had spent for this information! Thanks!

    15. Fantastic beat ! I wish to apprentice at the same time as you amend your web site, how can i subscribe for a blog site? The account aided me a applicable deal. I were a little bit acquainted of this your broadcast provided bright clear idea

    16. Loving this short report! You may not discover how happy I am that I surely could find this site. In case you ever want to mail suggestions to me, please do!

    17. Hey I know this is off topic but I was wondering if you knew of
      any widgets I could add to my blog that automatically tweet my
      newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.

    18. Hello this is kind of of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML.
      I’m starting a blog soon but have no coding expertise so I wanted to get guidance from someone with experience. Any help would be enormously appreciated!

    19. Most pet coverage deductibles are $50.00 for each accident category.

      Professional coverage program, although often Peyton Manning Jersey
      expensive, can be a necessity for your personalized enterprise.

    20. Make a Diet meal plan over time. Try variations of
      recipes to make them edible. That’s both good and bad. They did not have enough essential fatty acids, also help improve constipation.

      my site … paleo mama

    21. CSS is designed primarily to enable the separation of document content (written in HTML or a similar markup language) from document presentation, including elements such as the layout, colors, and fonts.This separation can improve content accessibility, provide more flexibility and control in the specification of presentation characteristics, enable multiple pages to share formatting, and reduce complexity and repetition in the structural content (such as by allowing for tableless web design). *..

      All the best to you

    22. I’ve been browsing on-line more than 3 hours nowadays, but I never discovered any interesting article like yours. It is beautiful price enough for me. In my opinion, if all website owners and bloggers made excellent content material as you did, the internet will probably be a lot more helpful than ever before.

    23. I’m really loving the theme/design of your blog. Do you ever run into any browser compatibility issues? A small number of my blog audience have complained about my site not operating correctly in Explorer but looks great in Safari. Do you have any ideas to help fix this problem?

      Check out my web page :: outsource link building

    24. I’m not sure where you’re getting your info, but great topic. I must spend some time finding out much more or figuring out more. Thank you for magnificent info I used to be on the lookout for this info for my mission.

    25. You can actually use a SpriteSheep app which will generate spritesheet plus CSS code to use it.

    26. Grape Diet plan: Men and women who have adopted this grape diet program plan have reported weight

    27. As such, it mustn’t be too difficult to invest some time constructing a database of tables similar to what is suggested at where they’ve
      provided a sample database spec to use in a hotel room reservation application.

      A very convenient way to search for things on the web is
      to easily speak your quest term. Trading invites a number of
      sites is extremely frowned upon within the exclusive Bit
      – Torrent community mainly because it allows anti-piracy groups to
      infiltrate private trackers with less effort.

    28. If no one is available to speak with you and no suggested return-call time is given, or if you are a
      nurse. This typically occurs overnight, as well as diminish the agencies reputation.
      Although interviewing with an employer, you should make sure that you are informed well enough on the topic.
      Regardless, if you would like to see expanded throughout the business
      sector in Chicago. But if you are looking for a
      temporary or half-time job or contract work.

    29. Magnificent beat ! I would like to apprentice while you amend
      your web site, how can i subscribe for a blog site? The account aided me a acceptable deal.

      I had been tiny bit acquainted of this your broadcast offered bright clear concept

    30. Hi guys if you can’t earn any money online
      try – bluehand roulette system – it earns me extra money
      everyday, just google it

    31. I read a lot of interesting content here. Probably you spend a
      lot of time writing, i know how to save you a lot of work,
      there is an online tool that creates unique, SEO friendly posts in seconds, just search in google – laranitas free
      content source

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>