State saving navigation with CSS

A common feature of most web navigation systems is the "active" state, e.g. the page you are currently on is highlighted in some way using an additional CSS class.

This effect is easily achieved when using somekind of back end CMS to power your website. For example WordPress automatically assigns a class of "current" to links which are active. This makes it really straightforward to hook into with a basic CSS selector, eg:

#nav ul li.current {border-bottom: 2px solid red;}

(this is purely an example and would probably look pretty horrific.)

Achieving the same effect with a more basic site (with no CMS) can be a little trickier. You can either re-make the nav code in each page and add the class in manually (don't do this). This is naff though as it creates duplication all over the place, meaning making changes to your menu would be a nightmare.

A better solution would be to code a single version of your menu (keep it in an include file), then use CSS selectors to point out the "active" item. Below is a quick method for doing this…

Step 1. The basic HTML:

This is a very bog-standard UL > LI > A structure, the only difference being we have given each list item it's own unique #ID with the prefix "nav-".

Step 2. Building our pages:

The next step is to build each of our pages. For each page we will add a #ID to the body tag, matching the #ID we set in our navigation. eg:

About us | Fake Company Ltd...

Step 3. The CSS magic…

Now we have our two matching #IDs setup for each of our pages/links, we simply need to hook them together with a bit of CSS:

body#about #nav-about a {
 border-bottom: 2px solid red;

This statement simply selects the A tag within the #nav-about LI on any page that is rapped in a body tag with the #about ID... Simples ^.^

There you have it, a simple method for creating that "active" state without butchering your HTML. It's worth also noting that using a body id can help in many other areas, for example: if a design requires a different layout on a single page, you can hook into the body id to apply styles to this specific page – meaning you don't have to create any additional classes/ids 

Top livechat