Building Faster Websites with CSS Sprites
Using CSS sprites allows you to greatly increase your websites speed by using single image files that contain multiple graphics. In other words, when you have many images to be used, instead of having them as different individual files, we combine them into one. Therefore, the client computer only downloads one image for all the different graphics to be displayed.
Quick Nav:
Benefits of CSS sprites
Using CSS sprite images on your website is the best way to quicken up the loading time of your images and is also the best way to keep up with today’s best web design practices.
CSS sprites decrease the loading time of images on your web pages, and can significantly lower the number of requests that your website makes which can drastically lower total page load time.
If you need more reason to use sprites, consider that most of the top sites out there are using them: Apple, Amazon, Yahoo… Tutorial9 :P
Materials Needed:
- A navigation menu (with multiple states other than the normal state, you may download the sample).
- Measuring application (err, you can try with a real-life ruler but Photoshop, Slammer or XScope would be better).
- A code editor (preferably, Notepad++ on Windows or TextWrangler on Mac, both free. I used both TextWrangler and Coda).
Image – Step 1: Set up each individual navigation menu image states
Since this tutorial is not focused on designing beautiful navigation bars, we’ll use pre-made ones. Don’t worry, there are plenty of Photoshop tutorials on Tutorial9 to teach you that, browse around!
Need a pretty navigation bar?
Download the source files here.
In the source files, there are 3 separate files for the navigation bar’s normal state, hover/rollover state and clicked state.
We’ll teach you how to combine them yourself in the next step. But you can always use the one combined image of all 3 states provided in the source files.
Step 2: Image – Combine all 3 navigation bar image states into 1 image
Right now, we have 3 separate PNG files for the 3 different states. It’s time to copy-paste them together into 1 image just as shown above.
A personal tip.
Usually, what I like to do in this step is (in Photoshop) make the background invisible so that all you have left are the buttons themselves like this:
![]()
Then, I go to Image > Trim:
![]()
Select Transparent Pixels and check all the sides to trim away:
![]()
So, now, you have a concise image of the buttons, nothing else. (Note that I made the background visible here):
![]()
Now that we’ve trimmed away correctly all the 3 states, let’s merge them into 1 image.
There is no standard way of doing this, you may be used to your own way of copy pasting but for the sake of example, start by opening up the normal state then press CTRL or CMD + a (select all) and CTRL or CMD + a (copy)just like below.
Create new document (CTRL or CMD + n).
Copy pasting tip
We copied the navigation bar before making the new document so that Photoshop will automatically know the width and height of the navigation bar.
You can see from the new document panel that the height of one navigation bar is 52. Since we’d like to put 3 states in this document, that’s 52 * 3 = 156. So let’s change the height of this new document to 156.
Then, paste the normal state of the navigation bar into the new document.
Move it to the very top of the document.
Repeat this process 2 more times or according to the number navigation bar states you have.
Paste and align the hover state of the navigation bar right below the normal state.
Lastly, paste and align the clicked state of the navigation bar right below the hover state.
If you have aligned all 3 states correctly, they will fit into the new 489 x 52 document perfectly just like so:
Step 3: Image – Measure the height of each buttons
Important: Get something to write on, whether a new text file on screen or a piece of paper for this next step ’cause we’ll need to write down the width and height for each button.
To easily determine the height of the buttons, we can look back on the height of each navigation bar for obvious reasons.
Tip for measuring in Photoshop
Use the Ruler Tool in Photoshop to easily measure things in your document.
![]()
In the screenshot below, the Ruler Tool is used to measure the height of the Home button.
![]()
Also, move the navigation bar below the navigation bar you want to measure one pixel down to see its edge.
![]()
After measuring the height of the buttons, we now know the height of each button is 52px.
And since all of the buttons have the same height, all of the buttons will all be 52px.
Step 4: Image – Measure the width of each buttons
Now, to measure the width of each buttons is a bit more complicated.
As mentioned above, the horizontal gap between each buttons should preferably be even so that when you divide the gap width into 2, one side will not be wider than the other. This is optional, though.
Here the width of the gap between each button is 16px.
When divided into 2 sides, each side of the gap will be 8px.
Tip to keep measurements in Photoshop
Make sure you have Rulers turned on (cmd + r) or go to View > Rulers.
Then, click on the vertical ruler and drag out a guide to the point where you would want your button to end.
Now that you know how wide your Home button will be, let’s measure it.
Use the Ruler tool again and measure from the left edge of the Home button to the guide we made as shown in the last tip, like this:
You can see the width in the Ruler tool panel:
Repeat the same process for all the other 2 buttons.
Step 5: Image – Width and height of each buttons
Step 6: CSS – setting up the navigation bar
Here comes the coding! I hope you already understand a bit of CSS and HTML. If not, then you can just go ‘head and copy-paste the codes below, :P.
First let’s create a DIV for our navigation bar in our HTML document and name it “navBarContainer”.
<div id="navBarContainer"> </div>
Now, let’s style this DIV in an external CSS stylesheet.
Linking an external CSS stylesheet to an HTML document
Put this line of code into the <head> tag of your document:
<link rel="stylesheet" type="text/css" media="screen" href="stylesheet_name.css" />
Like this:
<html>
<head>
<link rel="stylesheet" type="text/css" media="screen" href="stylesheet_name.css" />
</head>
</html>
Continuing on with styling the “navBarContainer” DIV.
In the external CSS, let’s write down the width, height and margin of the DIV that contains this navigation bar. It’s very easy to do so since we’ve already determined the width and height before.
#navBarContainer{
width: 489px;
height: 52px;
margin: 0 auto;
}
Note: the height for the navigation bar is 52 pixels tall, not 156 pixels. This is because we’d like to show only one navigation bar at a time.
Next, we’ll show how to use HTML lists to display links. This is a much more structured way for links.
Step 8: CSS – Using HTML lists (ul tags) for the navigation bar links
Let’s continue to code our HTML document.
We’ll now add the lists for each link:
<div id="navBarContainer">
<ul id="navBar">
<li id="navBarHome"><a href="#">Home</a></li>
<li id="navBarServices"><a href="#">Services</a></li>
<li id="navBarAboutus"><a href="#">About us</a></li>
</ul>
</div>
By default, HTML lists are structured on display as vertical bullets.
To make them flow horizontally, we’ll use “none” for the “list-style” attribute. We’ll also have to use “inline” for the “display” attribute.
ul#navBar{
width: 489px;
height: 52px;
margin: 0 auto;
list-style: none;
}
ul#navBar li{
display: inline;
}
So, instead of this:
We have this:
Step 9: CSS – adding images for each links
This first step is useful to still display the links as text whenever CSS has been turned off in browsers and the images aren’t available.
Add this code to do so:
ul#navBar li a{
height: 52px;
float: left;
text-indent: -9999px;
}
The “-9999px” was not a typo, this is too keep the text links off the screen if CSS is turned on. If not then the text links would overlap the navigation bar images.
Now to display some image for the home link!
ul#navBar li#navBarHome a{
width: 126px;
background: url(neonBlackNavBar.png) no-repeat 0px 0px;
}
Ta-da! Our first link is set up:
By the way, we changed our body background to #131313.
For the other 2 buttons, we apply the same codes but we change their background positions and widths.
Here’s the code for the “Services” button:
ul#navBar li#navBarServices a{
width: 179px;
background: url(neonBlackNavBar.png) no-repeat -126px 0px;
}
“WAIT! How’d you get that “-126px”?! Good question.
Since we used a sprite image, we need to ‘cut’ the images inside the sprite image.
We do this by specifying the background position.
Since the “Home” button x-axis was at 0px, the “Services” button (obviously, come on! :D) must begin where the “Home” button ended. And that is 126 pixels.
Now, here’s the code for the “About us” button:
ul#navBar li#navBarAboutus a{
width: 184px;
background: url(neonBlackNavBar.png) no-repeat -179px 0px;
}
And we’re done!
Actually, no we’re not done, the image above is a pitfall.
The “About us” button does not start at -179px just because the “Services” button ended there.
The correct calculation is (width of “Home” button) + (width of “Services” button). Therefore, the “About us” button begins at -305px.
Now, we’re truly done, I promise.
Step 10: CSS – adding hover states to the navigation bar
Adding hover states owns the same principle as adding the other 2 links. We just move their background positions.
For the “Home” button, we simply move its y-axis background position to where the normal state navigation bar ended, like so:
ul#navBar li#navBarHome a:hover{
background-position: 0 -52px;
}
Now, when you hover over the “Home” button, you’ll see its hover state.
Let’s apply the same principles to the “Services” button.
ul#navBar li#navBarServices a:hover{
background: url(neonBlackNavBar.png) no-repeat -126px -52px;
}
We’ll get this:
Lastly, to the “About us” button.
ul#navBar li#navBarAboutus a:hover{
background: url(neonBlackNavBar.png) no-repeat -305px -52px;
}
Preview:
Step 11: CSS – adding clicked/active states to the navigation bar
Given the keyword “active” for clicked link states, I really, REALLY hope you can already do this part yourself.
Here are the codes for the hover states for all 3 links:
ul#navBar li#navBarHome a:active{
background-position: 0 -104px;
}
ul#navBar li#navBarServices a:active{
background: url(neonBlackNavBar.png) no-repeat -126px -104px;
}
ul#navBar li#navBarAboutus a:active{
background: url(neonBlackNavBar.png) no-repeat -305px -104px;
}
More Ways to Speed Up Your Website
If you’re a speed junkie, then you’ll love these great articles that explore even more ways to reduce load time of your sites:
132 Comments
thanks for the tutorial! yours was the most explanatory i could find on the web :)
i encountered a problem when i applied the concept to my website. the navigation bar seems to be misaligned right of center. any suggestions on how to fix this?
thanks, again!
Flag as inappropriateexcellent! thanks for the help, this helped me understand sprites :)
Flag as inappropriateHi,
Thank you for this great instructions. I followed to the end, and it works excellent in Firefox, but in IE8 only first of four elements are inline, and other three are positioned few pixels below.
Open IE8 and take a look at here:
http://electrical-engineering-portal.com/
Is there some part of css code only to apply to IE browsers?
Thank you in advance!
BR,
Flag as inappropriateEdvard C.
That was exactly what i was looking for : )
Flag as inappropriateYou have listed some very nice sites here.
Thanx for sharing this
Using sprites on a site build now. Great technique that cuts down on file size and server requests.
Flag as inappropriateHey I have recently built my first sprite navigation and I have to admit that it’s really simple once you get your head around it! Instead of uploading multiple image slices to the server your only sending 1 which means only 1 server request! This technique can be used for other things not just navigation. Thanks for sharing this blog it has really helped me.
Flag as inappropriateThanks for the tutorial, works a treat.
Flag as inappropriateCheers for this, great tutorial.
Flag as inappropriateYour website is incredibly beautiful and useful. I have taken liberty to add this article to my CSS aggregator site. I hope you wont mind that.
Flag as inappropriateThanks for the article…
Flag as inappropriateTHanks for the great tutorial.
one question though. everything works great in IE8, however when viewed in firefox, the images shift downward out of position when clicked….
any ideas???
Flag as inappropriateFigured it out , i added :
margin:0;
padding:0;
to the second step in in part 9 ;
thanks for the tutorial , very helpful
Flag as inappropriateThank you very much! This is very helpful, I have been wondering how to do this for a while.
Flag as inappropriateCool tutorial thanks for sharing
Flag as inappropriateThese are great tutorial. I wanna be.
Flag as inappropriateWow, the states on the hovers are terrific and also the copy and pasting tip, so simple yet not fully adapted yet! Thank you.
Flag as inappropriateThis looks really interesting I can’t wait to try it!
Flag as inappropriateThis was a great tutorial, it helped me understand a lot of it…but it only talks about horizontal navigation, what do I do to get it to work for a vertical one? I’m probably just thinking too hard or something. @.@ I’ve been searching for a while looking for vertical CSS Sprites.
Flag as inappropriateit should be pretty easy by following the theory of this tutorial, just make sure each navigation item has the same width to ensure a good finish.
Flag as inappropriateGreat post . Thanks159
Flag as inappropriateGreat post . Thanks152
Flag as inappropriategreat i never seen before.47
Flag as inappropriateits very nice. Great post
Flag as inappropriateNice post …
Flag as inappropriatebut I have a query….Is there any CSS property to make font smooth in IE?
Nice tutorial man it will really gonna help..
Flag as inappropriatecan you tell me ..Is there any CSS property to make font smooth in IE?
this tutorial is the worst tutorial ever you dont even explain why you got so much going on in the CSS names ex….. #navbar li #navbar a… to much shit is going on… your horrible and got me so confused….
Flag as inappropriateHey, Mikey,
Sorry you don’t quite understand the CSS coding. No worries, I didn’t understand them at all when I was only starting out either.
If it is the DIV names that are confusing you, well, you have to get used to giving your elements proper names when coding in CSS.
As for having a long code, we have to accept that as that is how it works.
Take your time when learning, Mike. You don’t become a CSS guru overnight.
Also, take 5 deep breaths before commenting on posts next time.
Flag as inappropriateUseful Tutorial, Great Post.
Flag as inappropriateNice tutorial. Thanks for sharing.
Flag as inappropriateNo problem at all.
Flag as inappropriateHello friend :)
Flag as inappropriateThis is an awesome tut. Thanks very much for letting people know about this technique. This is the first time I work with CSS sprite and I’m very impressed :D. It definitely helps we to save time (both designers and web users)
However there were some mistakes that I found out during the time followed your tut:
1. At the very first step with CSS you forgot to determine the width of the #navBarContainer (so this div is 52px high and… 0px wide). Therefore, I (and other poeple – I think) cannot see the result of the Home button (also the other buttons). I fixed it by adding this line ” width:auto; ” (I prefer to use auto, much more easier for the next steps). From that point, the line ” margin: 0 auto; ” cannot be used anymore. I used ” margin-left: 25em; ” to replace it (so the navBar will be aligned in the middle of the screen as normal)
2.Someone complained about multiple lines, I got this problem too when I followed your steps. But the two CSS lines that I fixed and added above solved this problem. It’s hard to explain how do they work but… this is CSS :D it’s quite a bit abstract isn’t it =)
Anyways, thank for this nice tutorial. Hope you will fix your page soon, so other one won’t be wondered anymore ;]
Hello, Son Le,
Thanks for the feedback and kind words, first of all.
Secondly, the width of the navBarContainer DIV was determined in Step 6 in the code. Not sure if you saw that but I’m sure it’s there, :).
Thirdly, about using margin-left. A little problem with that is when the font size increases then the navBar will not be horizontally aligned anymore.
Lastly, CSS is quite abstract, isn’t it?
Again, thank you for taking your time in writing the reply!
Flag as inappropriateAm i missing something or do you have negative numbers specifying the position of the images?
Flag as inappropriateHey, Jason,
Nope, you’re not missing anything, we are, indeed, using negative numbers to reposition the images.
Let me try to explain it this way, let’s hope this makes sense.
Imagine the most top left pixel of the image is right on the point of origin on the X and Y-axis.
Once put that way, the rest of the bottom part of the image will be sitting on the negative Y-axis, won’t it?
We should also note that all digital interfaces are calculated this way. The top left of a window is always on the point of origin on the X and Y-axis.
Flag as inappropriatethanks! fast and easy…
Flag as inappropriatehi nice tutorial really help me to do more faster opening the page. but still doing more
Flag as inappropriatecan u tell me? how we can fix the pixels in different browsers , because in internet explorer 6. my blog preview is not adjusted
plz see
http://alisoft7.blogspot.com
and tell me
thanks
Awesome technique! Will definitely use it for other separate images on the site as well. Too cool…
Flag as inappropriateThank you, I will try it :)
Flag as inappropriateVery welcome, you have fun, now! It’s a beautiful technique, :D.
Flag as inappropriateAt first it took a while to get the hand of this technique, but I can safely say that it’s worth it. I can’t believe anyone would still use those bloated JS image replacement techniques anymore.
I’ve been wanting to store an entire site’s images in one large .png sprite for a while, if only to see how efficient it is. YouTube does this, but I can’t trouble myself to do so.
Flag as inappropriateYes, I’m so glad we don’t have to use JavaScript for rollover images anymore!
Flag as inappropriateNice tut, but when i tried using it, the menu bar breaks off into 4 lines. Its a navbar consisting of 7 links. I’m confused. I’ve tested it on chrome, ie, opera, etc: They’re all the same!
Flag as inappropriateSorry, for replying so late.
Wha? Are you sure? If you could post some screenshots, that’d be great, :).
Flag as inappropriatenice tutorial+
Flag as inappropriateI’ve recently ventured into the world of CSS and am just finishing up my first site where I did all the markup myself. I used a sprite for the navigation and in firefox and safari everything works perfectly, however, in Internet Explorer the alignment is all off.
I’ve tried several suggested workarounds but nothing has helped to remedy the problem. Does anybody know of a way to fix this? http://www.longballrally.com
Flag as inappropriategreat article to work ok
Flag as inappropriateI guess the only thing I would add is outline: none;
ul#navBar li a{
Flag as inappropriateheight: 52px;
float: left;
text-indent: -9999px;
outline: none;
}
Ah, yes, point taken.
Flag as inappropriateDefinitely worth the read. Sprite… aight!
Flag as inappropriateThanks very much. This is a thorough and useful tut…
Flag as inappropriateNo prob.
Flag as inappropriateThis is so so old school. It was a new thing round 3 years ago.
But as I see people find it useful…
Flag as inappropriateLol, yes, 3 years ago, it was the new kid on the block and now it’s Dreamweaver’s bully.
Flag as inappropriateThank you very much for the tutorial. It is extremely well written and easy to follow. Great job :)
Flag as inappropriateThanks! Glad it turned out that way, :).
Flag as inappropriateN1ce post
Flag as inappropriateSprites can be used with Jquery quite nicely if you want to add cool flashy effects to your menu, without using flash. There’s a lot of different libraries like mootools & scriptaculous. Here’s one article about it : http://www.alistapart.com/articles/sprites2/
Flag as inappropriateIf I can do it I’m pretty shure anybody can do it.
I always interest in CSS sprites but haven’t found a good single post until now.
Thanks.
Flag as inappropriateThank ya, I tried my best to explain it as easy and as clear as possible for you.
Flag as inappropriategreat post, thank you very much
Flag as inappropriateNewbie to sprites but you can get rid of that link border that appears around the active DIV on click. I usually set mine to something like this…
a {
Flag as inappropriateoutline-style:none;
outline-width:medium;
text-decoration:none;}
Funny, before reading this I was actually sticking together a couple of images in the spirit of sprites.
Nice one.
Flag as inappropriateNice post. This will come handy for my forthcoming projects. I’ve read this similar kind of tut while ago at http://www.webdesignerwall.com/tutorials/advanced-css-menu/
Thanks for this wonderful post Alexis.
Flag as inappropriateLol, thank YOU for readin’.
Flag as inappropriateGreat article. Tnx. I will use this tecnic for a client job (drupal site). Tnx again.
Flag as inappropriateSprites are the way to go check out http://www.sitv.com me and a co-worker knocked out this site using sprites for the multiple level nav!
Flag as inappropriateOh, WOW, just read all the comments on here!
Thank you so much for the positive comments, y’all!
I got some replies below.
—–
Hey, Deaner666, you mentioned, “The hover and active states are exactly the same, so why repeat them in the sprite image? You only need the two rows of buttons (saving on image size), and can use the CSS active states to refer to the same part of the sprite as the CSS hover states. Or am I missing something?”
Uh-oh, that means the active state isn’t too visible.
Well, if you try the demo then on the active states, you can see the top part of the buttons are a bit “pressed”.
That’s why there are 3 rows, the active states have a different style than the hover states, :).
As David mentioned, yea, they’re not too visible, huh? Lol, sorry ’bout that.
Flag as inappropriateIt works great Alexis, and it’s very nicely explained :) Outstanding work!
Flag as inappropriateThanks, Dave! Mucho respect.
Flag as inappropriateCool, love css sprites! Neat one!
Nahid
Flag as inappropriateAntsmagazine.com
I think in step 9 there´s something wrong, to get to the About Us button, don´t you have to do (home button width+services button width)?
I think it´s that way, but i´m just a newbie in CSS so i´m not sure.
Anyway, great tutorial! and this blog, this blog is amazing!!
Flag as inappropriateOMG! Thanks for pointing that out!
Yes, you’re right.
The following sentence, “The correct calculation is (width of “About us” button) + (width of “Services” button).” should be “The correct calculation is (width of “Home” button) + (width of “Services” button).”
We’ll correct that ASAP, thanks again!
Flag as inappropriateGreat article. This is a great way to speed up your website… especially for crappy browsers like IE. One thing to note though, when using them like you are… make sure to put a “overflow:hidden” on the anchor tag to avoid the long click box. Great tut!
Flag as inappropriateExcellent post, CSS sprites are definitely something every designer should know about.
Flag as inappropriateI’ve started to implement this for menus, icons and all other sorts of small graphics and I love the technique.
The only problem is when the sprite is a PNG, IE6 PNG fixes don’t like it this technique (normally causing the background to repeat itself for every one pixel), so for the time being I’ve got an IE6 stylesheet which changes the background images to a GIF.
Nice post.
Flag as inappropriateThat’s true, sprites are excellent, but there seem to be no way to make them work with PNG images and IE6 with fix png.
Unless I have done enough research, the later completely brakes the background positioning CSS capabilities, rendering sprites unusable… Annoying.
Would anyone have a solution on this one?
PNG background images + IE FIX PNG + Sprites that is.
Nice an very clear post, thanks.
Flag as inappropriateYes, CSS sprites is really a good technique to reduce number of HTTP requests and hence faster the page download. There are some cons too like it increases the combined image size and difficult to maintain (you can’t just replace a image if you don’t like any of them later), but if you have lots of images and less likely to change in future then these disadvantages can be ignored.
Flag as inappropriateNow this is wat is call website optimization . Very very useful. Thank you.
Flag as inappropriateThe hover and active states are exactly the same, so why repeat them in the sprite image? You only need the two rows of buttons (saving on image size), and can use the CSS active states to refer to the same part of the sprite as the CSS hover states.
Or am I missing something?
Flag as inappropriateThe problem is that the changes between hover and active state are a bit too subtle to notice in these images—I may try to make the changes more obvious so no one else questions why this seems this way.. I think the point Alexis was really trying to make is that you can have more than just 2 states wired to a single image :)
Flag as inappropriateAh yes… on closer inspection there is a very slight difference in the active state images… I’m looking at it on Windows, which has a lower gamma than MacOS, which I’m gathering was used for the tutorial, so the difference is probably more slight than was intended.
Flag as inappropriateExplained VERY well. Another great tutorial, I love this site. Thanks!
Flag as inappropriatenice tutorial, i like sprites.
Flag as inappropriateA standard technique now and it’s really surprising that people don’t use it. Good tutorial.
Flag as inappropriateYes, that’s exactly what I always wanted to know. I’ve seen this technique before and I find it very useful but I wasn’t really sure how to achieve this. Thank you very much, I’ll use it!
LBrother
Flag as inappropriate:D, yes, it took me a while to understand it too.
I’m very honored to have “taught” you these sprites, haha.
Flag as inappropriatethis looks great, does this technique work across all browsers…?
Flag as inappropriate(do you need to add any IE script?)
All modern browsers & IE6 should be able to handle sprites :)
Flag as inappropriateNow this will be mighty helpfull for me in the future. Thanks a lot!
Flag as inappropriate