Daily Tips & Tricks for Web Enthusiasts

How to Easily Style the Current Navigation Element

Let’s say you have a website with some navigation elements:

<nav>
    <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/blog/">Blog</a></li>
        <li><a href="/about/">About</a></li>
    </ul>
</nav>

Now, imagine you want to make the active navigation element bold. That is, when you’re on the home page, the Home link should be bold; when you’re somewhere inside the blog section the Blog link should be bold, and so on.

You might be thinking about writing some code on the server that spits out a special class for the current section’s navigation link. That would work, but it isn’t going to scale well as more sections are added.

But there’s a better way!

Let’s start by adding some classes to the navigation elements:

<nav>
    <ul>
        <li><a class="home" href="/">Home</a></li>
        <li><a class="blog" href="/blog/">Blog</a></li>
        <li><a class="about" href="/about/">About</a></li>
    </ul>
</nav>

Now, for each section of the site, add a matching class to the body element, like this:

<body class="home">

Now, with this CSS, the current section’s navigation element will key off of the body class:

body.home nav a.home,
body.blog nav a.blog,
body.about nav a.about {
    font-weight: bold;
}

Nothing dynamic, and no server-side coding required!

If a new section is added to the site all you need to do is add the new navigation link:

<nav>
    <ul>
        <li><a class="home" href="/">Home</a></li>
        <li><a class="blog" href="/blog/">Blog</a></li>
        <li><a class="about" href="/about/">About</a></li>
        <li><a class="contact" href="/contact/">Contact</a></li>
    </ul>
</nav>

Then add a new selector to the CSS:

body.home nav a.home,
body.blog nav a.blog,
body.about nav a.about,
body.contact nav a.contact {
    font-weight: bold;
}

There you go!