CSS Sprites – Easily Use CSS To Replace Images

May
28

24 Comments - LEAVE A COMMENT

If you’re not using CSS Sprites (also known as the CSS Image Replacement Method) you should be. Many coders seem to fear this easy and basic way to use images with CSS and I’m not sure why.

The benefits of CSS Sprites are plentiful, but you (and your visitors) will benefit from this method ten-fold. For the coder it’s less slicing and cropping of images, and for the user it rids us of that annoying image loading flash when you use CSS to replace background images.

I’ll take you through some quick steps to get started with CSS Sprites.

First, fire up Photoshop (or your graphic editor of choice).

For this example we will start easy and make a background (and hover state) for one tab.

First Create a new document (CTRL + N) width a width of 100px and a height of 50px. Than fill in the background with the color of your choice. I’m using black (#000000).

Next, click on the shape tool and select the rounded rectangle (SHIFT + U). Drag the shape until you get a nice looking tab. Double click the shape’s color box and choose a color for your tab. I’ve chosen red (#ff0000). Now, choose the move arrow and drag the shape so the bottom half of the rounded rectangle is outside of the viewing box so it looks like this:

CSS Sprites - Tab

Now, let’s make sure our tab is centered in the box. Select all (CTRL + A) and make sure the tab’s layer is selected. Click on the arrow (move) tool again. Now on the top tool bar click the “Align horizontal centers” icon (see image below):

CSS Sprites - Horizontal Align

Now, we can style our tab a bit. I’ve added an inner shadow to give the tab some depth (double click shape layer to have layer styles dialog appear):

CSS Sprites - Inner Shadow - Tab

Great. Now, the next step is up to you. You can leave the tab blank and have text overlay it through the HTML, or you can use a stylized text. I’ve chosen to use a font that isn’t available through CSS/HTML so I’ve added that to image. (To make sure your font is centered repeat the step above and “align horizontal centers”):

CSS Sprites - Tab

Great, so we have our first tab. Now we need to create our hover state for this tab. Duplicate your tab by right-clicking the title bar and selecting “Duplicate”.

Now on the duplicated tab I’ve changed the background color to a light blue (#00a8ff) (double click shape color box again to have color dialog appear).

Now, back to the original red tab I am now going to merge the two tabs together. For this example I am going to place the two tabs side by side, but that’s a preference left up to you. You can also stack the images on top of each other – or put them in any order you prefer.

So, right click on your original tab’s title bar and select “Canvas Size…” from the drop down. Click the LEFT arrow, and change the width to 200px (increase your canvas size by the width -or height if you are stacking) of your tabs).

CSS Sprites - Canvas Size - Tab

Now, to the right of your image you will have an extra 100px. Now, go back to your hover state image. Select all three layers and press CTRL + G. This will group all three layers into a folder. Now select the move tool (black arrow) and drag the image into the first image. Now adjust the grouped layer so it sits EXACTLY next to the original with the same height and width (you won’t see any of the transparent background if you do this correctly).

You should then have an image that looks similar to this:
CSS Sprites - Two tabs

And that’s it for the photoshop work!

Now, fire up your text editor.

Here is the HTML:

<a href="index.html" class="home" title="Home">Home</a>

And here is the CSS:


  a.home {
	background:url(tabs.gif) no-repeat;
	float:left;
	text-indent:-9999px;
	height:50px;
	width:100px;
	}

a.home:hover {
	background-position: -100px 0;
	}

Also if you want to use this as your “current” style (highlight the current page) you can add that class to the CSS so it would look like this:

a.home:hover, a.active {
	background-position:-100px 0;
	}
	

See the demo.

Not so hard right?? Check out the HTML and CSS for CSSgirl and you will see that for my main nav "images" I am using CSS Sprites. For this site though I used one large image that contained all the images for both the original nav and the hover states. So my HTML looks like this:


<div id="navi"><a class="home" href="http://cssgirl.com">Home</a>
<a class="about" href="http://cssgirl.com/about">About CSSgirl</a>
<a class="portfolio" href="http://cssgirl.com/portfolio">Portfolio</a>
<a class="contact" href="http://cssgirl.com/contact">Contact</a>
<a class="free" href="http://cssgirl.com/free">Free Resources</a></div>

And my CSS looks like this:

#navi {
	float:left;
	width:520px;
	height:48px;
	}

#navi a:hover {border:none;}

#navi a {
	background:url(images/navigation.gif);
	height:48px;
	display:block;
	float:left;
	text-indent:-9999px;
	}

#navi a.home {
	background-position:0 0;
	width:94px;
	}

#navi a:hover.home {
	background-position:-425px 0;
	}	

#navi a.about {
	background-position:-95px 0;
	width:91px;
	}

#navi a:hover.about {
	background-position:-520px 0;
	}	

#navi a.portfolio {
	background-position:-186px;
	width:128px;
	}

#navi a:hover.portfolio {
	background-position:-611px;	
	}

#navi a.contact {
	background-position:-314px;
	width:107px;
	}

#navi a:hover.contact {
	background-position:-739px;
	}

#navi a.free {
	background-position:-852px;
	width:98px;
	}

#navi a:hover.free	{
	background-position:-953px;
	}		

Get out there and try it! Show me how it turns out. I'd love to see what you guys can do with this. :)

Jump to Comments

24 Responses to CSS Sprites – Easily Use CSS To Replace Images

  1. Santhosh says:

    Nice trick to cache the image in one go and avoid many server hits.

    On the sidenote, I noticed that you syntax highlighting the html/css code by youself. There is fantastic automatic syntax highlighter in http://code.google.com/p/syntaxhighlighter/ which you might be interested in.

  2. Lindsey says:

    Thanks for the tip – I am definitely going to look into that! Sorry for the delay in answering. For some reason Akismet considered you a spammer… ?

  3. […] I’ve explained before how to use CSS Sprites for changing images, so I won’t go into too many more details on how to accomplish this, but to recreate this for your own site you will need to create one sprite for your normal tab, hovered and current/active tab. That’s three sets of tabs in one file. […]

  4. […] CSS Sprites – Easily Use CSS To Replace Images. […]

  5. noname says:

    this article angers me. whenever I see css used so wrongly it angers me. what were you thinking? this is a misuse of CSS! images belong as tags. that is what they were designed for. why mess with the logic of the browser that gives you an advanced and semantic way to display images in favor of a method that’s usually used as a “hack” in old gaming systems, though to the LACK of a better alternative. background images in CSS exist for adding background images, not rollover menus which are vital to the websites’ visitors. how would the web and web browsers advance if developers keep hacking websites and breaking the logic behind each component? for example, if tomorrow Firefox wants to come out with a new feature that applies to all images in a web page, it would have to include all /backgrounds/ as well. just think of what you’re doing before you agree to this technique. you HAVE the right tools, finally, unlike 10 years ago. now it’s time to use them correctly.

  6. Lindsey says:

    It’s easy to say whatever you like and not attach your name, eh?

    This is a technique that many, many, many sites use for navigation when they want to preserve a font not available to users and to have a background hover image technique that is preloaded with messing with javascript.

    Don’t like it? Don’t use it!

    And man up and attach your name to your thoughts. It is cowardly to go about ranting about what YOU think is appropriate without as much as attaching an identity to it.

  7. Lindsey says:

    Oh, and btw when CSS is disabled – like say for a screen reading device or mobile browsing (on some phones) the links display as a list.

  8. noname says:

    I guess you’re new here, welcome to the web – people use nicknames. also, people use comments to counter what an article is saying – Don’t like it? don’t enable it! instead you call your visitors cowards, you’re a really bad host!

    as for your point, I don’t see how “everybody else is doing it” justifies using a bad approach, a hack.

    Websites and programmers have been wrong before, you know. You’re just going with the flow… without thinking.

  9. noname says:

    oh, and about CSS being disabled, it’s good that you put in the effort, but it’s hardly enough, there’s a lot more potential in the browser that you’re disabling when you use a component in a way it wasn’t designed for. For example, take this page – http://www.lyricsfreak.com/p/pearl+jam/black_10203029.html
    it uses spirits for the icons. If I use my browser to resize the page’s text, I can see all the other icons hidden below the one that’s suppose to be visible. and resizing is a real basic feature for a browser to have… just think of all the features and browser extensions this might be affecting.

  10. Lindsey says:

    I don’t call my visitors cowards – I called you a coward. You want to act like you are the all high and might CSS guru – use your name, or your nickname – neither of what you are doing – oh, anonymous troll!

    It’s not a bad approach, nor a hack – it’s a technique used by many popular websites – and there are people out there who want to use, and know how – hence the article provided.

    As for the link provided in your second comment – I just went there and used Firefox to resize the text and I don’t see any issues – although I may be missing what you are pointing out.

    As for going with the flow? Negative. It’s a technique I enjoy using and works well. I never said I was right, or you were wrong. Take your own advice about “going with the flow”. What makes your flow the right one.

  11. noname says:

    When you use a property called “background-image” as if it was a tool to display regular images, you’re doing it wrong.

    You’re just too caught up in your own little world to admit it. just like you ignored my claims of you being a shitty host by saying “negative” and giving a silly explaintion.

    Trolls come to a website to pick pointless fights with others, I was trying to have a disscussion or at least counter your claims. hell, the only thing keeping you from being a troll is that you own this website. because otherwise all you’ve done here is obsess on what nickname I use and blab about your made up rules for the internet.

    I won’t be returning to this pathetic website, another superficial clone with unoriginal content. do you know how many articles there are about css spirits? the difference is now I know the author doesn’t want to be original either.

  12. migaber says:

    nice tutorial
    thanks for your help

  13. akeane says:

    This technique is well used and shows how the background position can be used. I personally do not see why changing a background via CSS on hover is wrong. I personally feel changing the background onmouseover via Javascript is ‘suspect’ since it is not reflected anywhere except in the Javascript.

    I love this technique and saves a lot of server access by having one image thus allowing one to have a more ‘pleasing’ navigation.

    I used this technique in a website and I think it worked great. greendoorsf.com

    Thank you… I just discovered your website today and have read a number of your postings. I hope there are more to come.

  14. […] Iíve explained before how to use CSS Sprites for changing images, so I wonít go into too many more details on how to accomplish this, but to recreate this for your own site you will need to create one sprite for your normal tab, hovered and current/active tab. Thatís three sets of tabs in one file. This is what your file should look like after you have finished styling it to your liking (click to enlarge): […]

  15. birkof says:

    Hey Lindsey, nice tehnique and it works great. I’ll add your blog to my Feed Reader. C’y

  16. Kieran says:

    I recently started playing around with CSS and have created a sprite based navigation for a site I’m developing. Everything works great in FF and Safari, but IE is killing me. For some reason in IE the alignment is all off. The buttons are in the correct order but after the first one they start to step down and out of alignment.

    http://img.photobucket.com/albums/v342/djsuperchink/Random%20Photoshop/untitled.jpg

    Any good workarounds or fixes for something like this? I’ve been searching around and can’t seem to find anything that works.

    Thanks, and keep up the good work.

  17. kevin bett says:

    i can’t believe “noname” for slating the author for using css sprites, just take a look at http://www.apple.com to see sprites in the navigation. It is a valid and widely used technique.

  18. Johns3n says:

    Well to be honest, noname is right.. using the CSS propeties these ways are and will be hack, since a hack is using something different that it was intended! Like tables for layout instead of tablular data…

    And just because that big companies like Apple use them, doesn’t make them right. Yes granted they work, and i for one am glad that CSSgirl provides the article for those willing to use this stupid hack (no offence towards the author, but in my humble opinion hacks are stupid and should never be used)
    But still glad the article is up, because the internet should be a place where you can find everything!! incl. hacks!

    And again! in regards to “it’s okay because the big players do it!” need I remind you that BMW uses Black Hat SEO… does that mean Black Hat SEO is okay now? Fakk no :P but in regards to the article, I disagree with the content, but a nice read ^^

  19. Paul says:

    I don’t consider it a hack, just because it isn’t common, or used frequently. If the background-position attribute is available, use it. If you want develop web sites the way they were meant, you would use a fluid layout instead of fixed. Not many sites do that either. Sprites in many ways have been used since the dawn of personal computers, so there is no reason why it shouldn’t be used with CSS and web sites.

    In fact, it definitely should be used with web sites, the main reason being because it optimizes them. Instead of making several calls from the client to the server, you only need to make one to retrieve the sprite. Many of the big companies do this because they understand efficiency and how to implement it the best.

  20. Steven says:

    I love this, I got my http requests down from 31 to 12 with this tutorial! Therefor getting my load times down, my bandwidth down and my SEO up!

  21. Nathan says:

    Haven’t read all the comments, so this may have already been said, but Lindsey’s approach does have one huge advantage: By using the background-image property instead of using an img tag, she has preserved the distinction between content and visual presentation, allowing her to change the appearance of her navigation in the future completely from the CSS. Good work, Lindsey! This is the way it should be done. =)

  22. Thank you a lot for sharing this with all folks you actually recognise what you are talking about! Bookmarked. Kindly additionally discuss with my web site =). We can have a hyperlink exchange contract among us

  23. Aubrey says:

    You go girl!!!
    Call “noname” whatever you like!
    If his b@lls are in a twist because it “should” be an img tag, HE CAN STILL USE THE FOUNDATION CONCEPT!!!
    Use a div, CSS its dimensions and overflow.
    Then put an image inside it.
    CSS img position: relative, top and left to where you need it and you are done.
    The only difference is that the img route may not cache (so you may have the img loading once per page) and the background will cache (in most cases anyway) – either way there is a drastic reduction in http calls.
    [And of course you should never discount the IE factor.;>}]

Leave a Reply

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