Dynamic navigation with PHP & CSS

One of the key approaches to web site navigation is to make sure your users know where they are moving around your site. One way to achieve this is to highlight the appropriate menu item for the page the user is on. This is easily done with a little CSS and PHP.

Let's get started

First, let's look at the code for the menu (this is assuming that your menu is an include file although it works fine if hard-coded into each page manually, which I don't recommend). It's your standard unordered list, nothing too fancy. The magic happens when we add to each anchor tag a line of PHP that will assign the 'current' CSS class when on the appropriate page:

menu.php

<div id="menu">

<ul id="nav">

<li><a href="page1.php" class="<?php if ($thisPage == "page1") { ?> current <?php } ?>">Menu item</a></li>

<li><a href="page2.php" class="<?php if ($thisPage == "page2") { ?> current <?php } ?>">Menu item</a></li>

<li><a href="page3.php" class="<?php if ($thisPage == "page3") { ?> current <?php } ?>">Menu item</a></li>

</ul>

</div>

Thanks to Andrzej for the tip on using the above method for allowing of multiple classes. Good call!

Looking at the first list item (that links to page1.php), notice how it requires 'page1' to be loaded to apply the 'current' CSS class. This is achieved by adding the following PHP code at the very top of page1.php, before the <HEAD> tag:

page1.php

<?php $thisPage="page1"; ?>

<HEAD>

<!-- Your page content here... -->

The CSS that styles the menu will include the 'current' class so when page1.php is rendered, class="current" is echoed, thus dynamically applying the style for you:

menu.css

#menu ul {
margin: 0;
padding: 0;
list-style: none;
}

#menu li {
display: inline;
}

#menu li a {
float: left;
display: block;
font: normal 1.0em arial,verdana,tahoma,sans-serif;
line-height: 1.0em;
color: #fff;
text-decoration: none;
margin: 0 10px 0 0;
padding: 10px 12px;
background: #000;
}

#menu li a:hover {
color: #fff;
background: #666;
}

#menu li a.current, #menu li a:hover.current {
color: #fff;
background: #444;
}

Enjoy!

Stay well.

Please complete all fields to submit your comment.
Thanks. Your comment will be posted shortly.




This is your Captain speaking

Hi, my name's Fred and I'm a web designer & developer from Ottawa, Ontario. I specialize in front-end development and the user experience but also enjoy server-side development, SEO, social media and supporting my peers in the community.

Follow me on Twitter
Call me on Skype

Recent additions to the Community