Your website most likely has a menu. When you click on a menu item and navigate to that page you need that menu item to remain highlighted to indicate to the user where they are. In this post we’ll examine a couple of ways to do and to NOT do that.


To achieve this effect on your menu you need to define a css rule with the style you need. Then you need to apply this rule to the active menu item.

Let’s see an example. Suppose this is your menu:

<li><a href=”/”>HOME</a></li>
<li><a href=”page1.php”>Page1</a></li>
<li><a href=”page2.php”>Page2</a></li>
<li><a href=”page3.php”>Page3</a></li>
<li><a href=”page4.php”>Page4</a></li>

You want to give your active menu item a blue background. You can use a css rule like this:

.active {

Then if you are in page2 above you can modify the code to style that menu item:

<li class=”active”><a href=”page2.php”>Page2</a></li>

However, this means that each page must have different html for the menu, since the active menu item must have the. What are your options here?

1) Put a different copy of the menu code in each page, adding the to the respective menu item as appropriate. Please DON’T ever do that as this makes it a nightmare to make even a slight change to the menu, e.g. to change a link of a single menu item.

2) Use a php code which inserts the text on the page as appropriate, eg.

<li <?php if(strripos($_SERVER['REQUEST_URI'], “page2.php”) ) {echo “class=’active’”;} ?> ><a href=”page2.php”>Page2</a></li>

This is often the best approach.

3) Sometimes you may need to use some logic that requires more info than just the request uri. Maybe it’s the category a post belongs to in WordPress, which wouldn’t be available at the time the menu is included. For these cases there is a stronger weapon available. It’s called Javascript. Just insert this block in each page and use it to set the desired class on the elements that you need.

<script type=”text/javascript”>
var element = document.getElementById("page2");
element.className = element.className + ” active”;

This of course assumes that you’ve given the id “page2″ to an element in your menu:

<li id=”page2″><a href=”page2.php”>Page2</a></li>