Dynamic navigation with PHP & CSS
January 7, 2010 CSS PHP/MySQL Tutorials
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.













This is just what I was looking for! A demo would be nice tho.
Posted: January 9, 2010
I was just looking for something similar to this, thanks a lot!
Posted: February 1, 2010
Hi, Tommy. Glad you found it useful. :)
Posted: February 1, 2010