Highlighting current page with CSS

With handy online resources such as List-o-Matic, its now easier than ever to use unordered lists to create navigation. As an extra help to users, why not highlight the current page in the navigation? A recent article on A List Apart called Keeping Navigation current, showed how to do this with PHP. Here’s an easy solution using CSS.

First we’ll set up our navigation list. I have chosen 4 sections for ease, and its best if navigation sections are kept short anyway:


    <ul id="navlist">
        <li><a href="index.html" >Home</a></li>
        <li><a href="products.html">Products</a></li>
        <li><a href="faq.html">FAQ</a></li>
        <li><a href="contact.html">contact us</a></li>
    </ul>

Next we need to add a unique class or id (doesn’t really matter which) to each of the section pages:


    <ul id="navlist">
        <li><a href="index.html" id="homenav">Home</a></li>
        <li><a href="products.html" id="prodnav">Products</a></li>
        <li><a href="faq.html" id="faqnav">FAQ</a></li>
        <li><a href="contact.html" id="connav">contact us</a></li>
    </ul>

Before we leave the HTML, on each of the section pages we need to add a unique id to the body tag:

<body id="home">

This allows us to specify the highlighted tab. After we’ve added the CSS styling for the menu, we add the css rules to highlight the correct tab. As all of these instances use the same rules, we can just list them all, seperated by commas, and the browser will apply the rules to every instance. These overrule the previous styles wherever is on the same page as .


    body#home a#homenav,
    body#products a#prodnav,
    body#faq a#faqnav,
    body#contact a#connav {
        color: #fff;
        background: #930;
    }

I’ve set up some basic pages so that you can see the navigation in action. This allows the navigation to be put into an external include file for ease of updating. The ‘decisions’ as to which button or tab to highlight all happens in the CSS file. This can also be used to introduce different coloured sections. Handy if the layout positioning stays similar and all you want to do is change the colour theme.