Including Navigation Code On All Pages (Even With Current Navigation Highlighting!)

Avatar of Chris Coyier
Chris Coyier on (Updated on )

You’ve seen this a million times:

<ul>
  <li><a href="#">Home</a></li>
  <li><a href="#">About us</a></li>
  <li><a href="#">Contact us</a></li>
</ul>

The classic menu HTML which you can transform into any number of beautiful things through CSS. You could include that in all your pages by putting it into it’s own HTML file (like “menu.html”) and including it on your pages with some kind of simple include statement like this PHP snippet:

<?php include_once("menu.html"); ?>

Now you need to add a class so you can indicate to your visitors where they are in your current navigation:

<ul>
  <li><a class="selected" href="#">Home</a></li>
  <li><a href="#">About us</a></li>
  <li><a href="#">Contact us</a></li>
</ul>

The selected class might switch out a background image or bold the text or something to indicate current navigation. This is great, except that now you have individualized this block of code for a particular page. Uh oh! We broke the entire usefulness of using the include statement. Doing it this way would require us to put this code on every single page and change around where we put the selected class.

Instead, let’s give every single link the menu it’s own unique class:

<ul>
  <li><a class="home"  href="#">Home</a></li>
  <li><a class="about" href="#">About us</a></li>
  <li><a class="contact" href="#">Contact us</a></li>
</ul>

This still doesn’t give us a way to single out individual menu items on individual pages. At least not all by itself….

Here comes the trickery:

Give each <body> tag on your pages a unique ID. Such as <body id=”home”> Then you can create CSS which will only affect the menu items when the menu link class and the body ID match:

#home .home, #about .about, #about .about, #contact .contact
{
Your CSS stylings here
}

What a great example of the beauty and efficiency CSS. Thanks Trenton Moss.