“Active” State in CSS Navigations

Blog » CSS/XHTML » “Active” State in CSS Navigations

“Active” State in CSS Navigations

PrintAugust 30th, 2009

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

Did You Enjoy This Post?

subscribeSubscribe via RSS ,by email, or by twitter to get all upcoming
tutorials and articles delivered straight to you.

Bookmark or Share this Post!

  • Digg
  • del.icio.us
  • StumbleUpon
  • Technorati
  • Twitter
  • E-mail this story to a friend!

Tags: ,

This entry was posted on Sunday, August 30th, 2009 at 10:05 pm and is filed under CSS/XHTML. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

44 Responses to ““Active” State in CSS Navigations”

  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.

Speak Your Mind…

Need to post HTML code?
Use Postable for your convenience.

Don't have an Avatar?
Set up a Gravatar image now!

Blog Blog Categories

Popular Comments Popular Posts

Recent Comments Recent Comments