Tutorials

Latest Word » Tutorials » “Active” State in CSS Navigations
Active State in CSS Navigations

“Active” State in CSS Navigations

Tags: ,

I am sure you have been on a website where the navigation has an “active” state, basically showing you which page you are currently on. Take a look at my top navigation, you should see that the “Blog” link is in its active state. This technique is what you will be learning today.

Take a look at the demo below to get a preview of what you will be creating. Also if you would like to download the PSD that we will be working with, go right ahead.

Active Navigation with CSS

Foundation – HTML

Start by creating your navigation with an unordered list. Be sure to assign a unique class name to each of the list items.

<ul id="topnav">
	<li class="home"><a href="index.htm">Home</a></li>
	<li class="about"><a href="about.htm">About Us</a></li>
	<li class="services"><a href="services.htm">Services</a></li>
	<li class="portfolio"><a href="portfolio.htm">Portfolio</a></li>
	<li class="contact"><a href="contact.htm">Contact</a></li>
	<li class="blog"><a href="blog.htm">Blog</a></li>
</ul>

Styling – CSS

Strip down the unordered list to bare bones. This will prepare us for the text replacement technique for each of our navigation links.

ul#topnav {
	margin: 0; padding: 0;
	list-style: none;
	float: left;
	width: 960px;
}
ul#topnav li {
	float: left;
	margin: 0; padding: 0;
}

We will be using CSS Sprites, this will basically allow us to have three states (Default, Hover, & Active) for each navigation link.

Active Navigation with CSS

/*--CSS Sprites - Default State--*/
ul#topnav a {
	float: left;
	display: block;
	height: 58px; /*--Specify height of navigation--*/
	text-indent: -99999px; /*--Shoot the text off the page--*/
	background-position: left top;
}
/*--CSS Sprites - Hover State--*/
ul#topnav a:hover {
	background-position: left -58px;
}
/*--Assign an image and width to each link--*/
ul#topnav li.home a {
	background-image: url(home_a.jpg);
	width: 120px;
}
ul#topnav li.about a {
	background-image: url(about_a.jpg);
	width: 147px;
}
ul#topnav li.services a {
	background-image: url(services_a.jpg);
	width: 157px;
}
ul#topnav li.portfolio a {
	background-image: url(portfolio_a.jpg);
	width: 182px;
}
ul#topnav li.contact a {
	background-image: url(contact_a.jpg);
	width: 179px;
}
ul#topnav li.blog a {
	background-image: url(blog_a.jpg);
	width: 175px;
}

Setting the “Active” State

We will be adding this “active” state by assigning an ID to the <body> tag on each of our pages. By assigning an ID to each page, we can now specify different properties and values depending on which page it’s on.

So for example, the homepage file should have the <body> tag set like this:

Home Page HTML

...
<body id="home">
...

and the About Us page like:

About Page HTML

...
<body id="about">
...

and so on. Each page should now have its own unique ID on the <body> tag.

Using CSS Specificity to override the default and hover states, we associate each body ID with its matching list item class to set the active state.

The Logic in Plain English
If it’s on the “home” page (body id=”home”) , set the “home” link (li class=”home”) to “active” (background-position: left bottom;).

Now we will apply this logic to cater for all of the pages.

CSS

#home li.home a, /*--Home Page > Home Link--*/
#about li.about a, /*--About Page > About Link--*/
#services li.services a, /*--Services Page > Services Link--*/
#portfolio li.portfolio a, /*--Portfolio Page > Portfolio Link--*/
#contact li.contact a, /*--Contact Page > Contact Link--*/
#blog li.blog a /*--Blog Page > Blog Link--*/
{
	background-position: left bottom;
}

Below is a visual demonstration of how all of this is working together.

Active Navigation with CSS

Conclusion

If anyone has any questions, concerns, or comments please feel free to let me know!

Need Navigation Inspiration?

Check out Design Bombs for some navigation inspiration!

CSS Navigation Inspiration

Related Posts

Author Bio

My name is Soh Tanaka and I am a Los Angeles based designer/front-end developer specializing in CSS driven web design with an emphasis on usability and search engine optimization. I also run a CSS Gallery which is updated daily with the best CSS websites from around the world. Come check it out!

You can learn more about me or Twitter  Follow me on twitter for more updates and resources!

Did You Enjoy This Post?

subscribe  Subscribe via RSS or by email to get all upcoming tutorials and articles delivered straight to you.

+ Add Comment59 Peeps Have Spoken Their Minds...

  1. edouard

    I don’t mind, but the first article ever written on this technique is from alistapart blog if I remember well …
    I like this stuff and you can add a little jQuery to fade between the states of your button.
    original post here : http://www.alistapart.com/articles/sprites2/

  2. MarinTailor

    Thanks for this tut! It is very usefull! =)

  3. Snoopy

    Hello,

    Am creating a dropdown menu, when i clicked on a main menu item i need to change the background color of the active link and this background color should remained as long my dropddown is opened. Here in ur demo u used three different images to set the different status of link , but is there a way in css to set “Active” State using background color. Thank for your help

  4. Sidi

    Your nav tutorials are awesome. Keep up the good work.

  5. smu

    Great tutorial!
    Is it possible to make this navigation with just one sprite?

  6. Norman

    Hey, that is one nice tutorial there. :)
    One thing tho, when you are using CSS sprites, why not putting ALL images into one big image? Take a look at http://www.apple.com – the whole navigation with all its states is one single image. Saves you a few more http requests ;)

  7. Yasser

    Great tutorial ,

    Thanks soh :)

  8. Barrie Tonz

    it’s = it is

  9. Hassan

    Since wordpress 2.7 or 2.8 there is this body_class function which add class to the body. But, is there a function already exist in wp to have pages a unique id?

  10. Soh

    @eduardo, thanks for that link! I love all alistapart articles, top notch stuff :-)

    @snoopy you can set the background-image: to none;, then specify a background-color: your_color;

    @smu, Yes, as Norman mentioned there is a way to have one navigation image.

    Instead of specifying the background src, you will be specifying the background positions like this:

    ul#topnav li.home a {
    background-position: 0 top;
    width:120px;
    }
    ul#topnav li.about a {
    background-position: -120px top;
    width: 147px;
    }

    Each nav that you adjust will have the increments of each nav width in negative pixels. Here is a quick sample of what it would look like (view source) http://www.sohtanaka.com/web-design/examples/active-navigation/index2.htm

    @Norman, I really do love the idea of one image for the sprite, but I’m also a fan of minimizing code, which is one reason why I chose to go this route. The fact that you have to specify each individual position for the default, hover, and active, it almost triples the amount of code you have to write/copy. But I guess in the end it saves more by using one image like apple.com.

    Either way though, I think they are both great techniques! :-) Thanks for the tip!

    @hassan, since wordpress throws in classes instead of IDs in the body tag, you can go ahead and use the classes instead.

    or you can add something like:

    <?php
    $url = explode('/',$_SERVER['REQUEST_URI']);
    $dir = $url[1] ? $url[1] : 'home';
    ?>

    <body id="<?php echo $dir ?>">

    Read more about it here: http://css-tricks.com/forums/viewtopic.php?f=2&t=2127

  11. Josh Stauffer

    Nice tutorial… In reference to Norman’s suggestion, I think there are pro’s and con’s to both approaches. Yes, one image uses less HTTP requests and I am not as concerned about the extra CSS code as I am about adding/removing nav images. Say you added a link, well now you have to jack with the CSS to get the dimensions worked out correctly for all the links. Sticking to the way Soh lays it out would be easier for the developer. I think it just comes down to preference.

  12. faardeen

    great tutorials..thank you but there are many ways through php and so on.

  13. Hassan

    @soh, I had hope that if there’s a native wp function for that, like body_id. I hate this type of coding! :)
    Thanks for the code.

  14. Kirana

    WoW…!!!very good, Thanks Soh…

  15. ngassmann

    @hassan WordPress dynamically adds the class to the pages/posts. I don’t understand why you would need to add that snippet.

    http://www.nathanrice.net/blog/wordpress-2-8-and-the-body_class-function/

  16. Tameshwar

    Its very useful logic for static page, when the data comes from the dynamic it will not work. I mean when i created a master template then we cannot give id to each body, because body comes only one time on the browser.

  17. Lazy Web Designer

    Great stuff!

  18. Heather

    I haven’t gone through this yet, but seeing anything from your blog show up in my rss reader makes me happy! Especially when it is a technique I was looking to learn how to do. Definitely saving to read for later.

  19. Soh

    @Tameshwar this technique is not only limited to the <body> tag. I use the <body> tag since its the highest in the tag hierarchy. You can always set a <div id="home"> right below the body tag, and dynamically assign an ID to each page and it will behave the same.

    @all thanks for your feed back and kind words :-)

  20. Ahmad Alfy

    Awesome, never thought of using the body id to use that!
    I used to add another class “active” but this is way much better
    I can use the same navigation code everywhere without worry

    Excellent technique!

  21. Danilo

    Thank you so much, this is the only tutorial that helped me to get the menu active state, thank you for sharing this.

  22. art

    never thought this way.
    I use one more class for li, something like class=”about active”, but may be this way better

  23. Janko

    Well done, Soh. I really like the idea and especially the demo :)

  24. Webcare

    Thanks for sharing how to highlight the menu state. This would really be helpful in creating one of a kind websites.

  25. Sarah

    Thanks for sharing how to highlight the menu state. This would really be helpful in creating one of a kind websites.
    P.S.: Forgot to add great post!

  26. Björn Rixman

    @soh, just a small note on your comment about using a single sprite for all nav items by switching bg position horizontally:

    If i remember correctly, IE might have issues with mixing keywords and numeric values in background-position:
    just to be on the safe side, instead of “-120px top”, write “-120px 0″

    great site by the way!

  27. Soh

    Thanks for the tip Björn! I didn’t know about that :-)

  28. siraj

    hi.. the tutorial is good. the only issue is… i m working on a drupal website, and its fairly huge one… now setting up classes for individual pages is very cumbersome. can we not have something dynamic here?

  29. Soh

    Just like I mentioned for wordpress, I’m sure drupal can assign a unique ID/class for each page. But again, even if you make dynamic class/ID’s your still going to have to make each unique image and also call out each class name. So I wouldn’t really consider going this route for a large scale site, its just not the wisest decision~

    So in your case I would stick with setting an “active” class to the active navigation. This way you only have one active state and its nice and simple in your CSS. Good luck!

  30. PolishPaul

    Finally, thanks to your post, i was able to get my menu going. Since I’m working on an ASP.NET page with a Master Page, i’m not able to set the ID so i simply wrapped my menu in a tag with the right ID. Thanks a bunch!

  31. DT

    Well done, Soh. I really like the idea and especially the demo :)

  32. Xaliber von Reginhild

    Great feature… :D But it seems it’s only applicable to static sites which use HTML? I’m a newbie in design, so I guess I don’t know much…

    Is there any way to apply this to CMS such as WordPress or forum engines? I’d like to have one… :mrgreen:

  33. china

    搞的不丑!
    Great!

  34. Metin Ucar

    Oh man, you saved my life. I’ve been trying to find a tutorial where I can learn about active state for a long.
    Thanks. Keep up the great work…

  35. Tim Collins

    thanks Soh, absolutely love your site. Keep coming back time after time, been looking for a tutorial on this too!

  36. Brian Enriquez

    You’re the man. I just walked through your tutorial and I’ve wanted to do this FOREVER, at least 5 months or so. And, now, I completed it in about an hour after some troubleshooting.

    Thank you, thank you, thank you.

    Here’s the site I implemented it on: http://www.hauteyogaqueenanne.com

    NOTE: I used to go to the Art Institute of Seattle for Web Design and Interactive Media. I withdrew in the summer time. Why? ‘Cause there are dudes like you all over the world that teach me magic every damn day. It’s 2:40am and my eyes are burned open by wonder.

    Thanks again.

  37. pixemotion

    Thanks for all your great tuts, you rocks !

  38. Mario Hernandez

    Can I set an “active” state on a sub-navigation like the one sample you have in your website? (http://www.sohtanaka.com/web-design/horizontal-sub-nav-with-css-jquery/). Could you let me know if this is possible?

    Thank you,

    Mario Hernandez
    Web Developer

  39. share

    is possible in this menu with “active”, put a submenu?
    if so you could put some tutorial porfavor, saludos.

  40. Kai Wang

    Hi there, thanks for the great tip. This tutorial guide through adding id to pages that have physical HTML files, what about pages that are dynamically generated (i.e. tag() pages)?

    Thanks!

  41. J DesigN

    cool !!

  42. Liminal Web Design Cornwall

    Nice tutorial, I only recently started doing image navigations like this as with so many people being hot on SEO its been text based navs.

    Great example though – thanks.

  43. Paulo Fino

    Hello!
    Thank you very much for this useful and easy to follow tutorial.
    Do you know whether it is possible to somehow attach the active state to anchors on one page?
    I am currently working on a website, designed as a single page with some dynamic blocks. And I need a simple menu that will scroll the page down to a particular section defined by an anchor. The only thing is I need the respective menu item (as well as the header of the respective section) to become active and keep its hover/active state until the user clicks on the ‘back to top’ link and changes the current anchor.
    Do you know of a possible solution?

  44. nikhil ughade

    hey SOH,
    Its a nice tutorial and the new thing i learn here is “Body ID”.
    Thanks for sharing it.

  45. bayu

    dear soh,
    i’ve tried to follow your tuts step by step but can’t achieved same result as your or the others.. can you help me, please?

  46. ashe

    Thanks for this tut! It is very usefull! =)

  47. Jacobo

    Is there a way to create a similar active state css navigation with also drop down menus added?

  48. Basil

    Good afternoon. I have read the information you have posted in his blog, and I want to express my gratitude. On the basis of your lesson, I created the same menu control on its website http://www.vmebelshop.com.ua. Due to the fact that you are very detailed and clearly explained to all points of constructing the menu, I do not know English, could not repeat your idea. Thank you from a beginner programmer from the Ukraine. I wish you success in all your affairs.

  49. Jen

    Could you use this active state with a jump link for content with overflow hidden on the same page? So instead of giving each body tag of a different html page the id, could you give the div tag with the named anchor you’re jumping to the id?

  50. Mark

    This is a great menu. Thank you for your work and your help implementing it.

  51. dh

    This is a great tut and I’m a big fan, but I think it’s important, especially for newbies, to make it obvious that the active id needs to be applied. Very easy to be copied without it.

    ul#nav a:active{
    background-position: left bottom;
    }

    Keep up the great work!

  52. Frank

    Nice, Super Script!
    Have long sought after this css active. The direct with the class for the link, I would never come out. Super page 1A. Keep it up, I am so happy thank you.

  53. Anything Graphic

    Is it possible to set an active state after following your tutorial on CSS Sprites w/out Using Background Images? I implimented some techniques from that tutorial with icons on my navigation, but I am now trying to get an active state to work and cannot… I’m flustered and was wondering if the master (you) had a workaround :-)

    Thanks dude!

  54. Anything Graphic

    So, I just figured it out… I feel retarded :-) All you have to do is:

    #home #navhome img, #about #navabout img, etc… {
    margin-top: -94px; /*however much you need to create the sprite animation*/
    }

    Sweet :-)

  55. Duane

    Watsup Soh. Awesome website you have here and great tutorial. I’m not sure if this is just the wordpress theme I’m using, but in IE the end of my menu overflows and continues under the top bit when I assign div id’s. I add the div’s above the custom page template tag. It works great in other browsers, but IE is giving me nightmares.

  56. Remonty

    Very nice menu, now i know the way to make my own animated menu :) thanks a lot!

  57. Lucas

    Im glad to know that there is still smart and hardwork people around the world. Since i’ve found your website i cant stop exploring and reading all the very-well made tutorials, witch already helped me a lot!

    Thank you for your work!

  58. Mike Kim

    Thanks for the dope tips and links!

    I hooked up active links on my WP theme by following the video on this link: http://css-tricks.com/video-screencasts/36-current-nav-highlighting-using-php-to-set-the-body-id/

  59. JOSH C

    U R THA MAN! THX 4 the free article bro.

    jm
    miami, fl

Speak Your Mind...

Post HTMLNeed to Post HTML Code? Use Postable to post code friendly html. *Wrap all html code in <pre></pre> tags.
Post HTMLNeed to Keep Updated with Comments? Subscribe to comments now.

CSS Gallery