Archive for August, 2006

Managing Global Menu Selectors Using Only CSS

Thursday, August 24th, 2006

One of the most important aspects of a usable navigation is the ability to know where you are. This is generally accomplished by using a visual indicator, like changing the color or size of a button. On this website, the menu item’s text color changes from orange to green, and an orange line appears underneath the text — all of which designates the section of the site your located in.

menu.png

One way to achieve that is to create a style for the menu item you want selected. For example, you can name the class “select,” and add it as an attribute to the menu item’s anchor element.


<ul>

  <li><a class=”select” href=”/events/”>Events</a></li>

  <li><a href=”/blog/”>News</a></li>

  <li><a href=”/contact/”>Contact</a></li>

</ul>

The problem with that method is that you have to manually add the select class to the appropriate menu item on each page. It also keeps you from storing the menu as an include file, because there isn’t a way to specify which menu item should be selected.

Fortunately, there is a solution, and it doesn’t involve any programming. The trick is to specify an ID attribute in the BODY element of each page that corresponds with a menu item. Using the technique below, I was able to put the menu in an include file and specify the correct menu selector, all with just CSS.

Menu Include File

The include file contains the HTML that makes up the menu. Instead of using select, I assign a unique class for each menu item.


<ul>

  <li><a class=”events” href=”/events/”>Events</a></li>

  <li><a class=”blog” href=”/blog/”>News</a></li>

  <li><a class=”contact” href=”/contact/”>Contact</a></li>

</ul>

Page Elements

On each page I set up a PHP include that maps to the Menu Include File.


<? include '../inc/nav.inc'; ?>

I also specify an ID attribute in the BODY element that relates to the section where the page is located.


<body id=”events”>

CSS

In order to turn on the selector for the appropriate menu item, specify the BODY ID and then the class related to the section’s menu item.


body#events #head ul li a.events,
body#blog #head ul li a.blog,
body#contact #head ul li a.contact
{
  border-bottom:3px solid #e3c45b;
  color:#7e9c45;
}

Using this method, all you need to do is update the Menu Include File if you want to change any part of the navigation. It’s a simple technique that doesn’t require any PHP logic or individual page updates.