Posts Tagged “active page”

I have always preferred including a menu file on my sites rather than repeating them on all the pages for the obvious reason that menu items sometimes change and it easier to change one file than change the links on all the pages that show that menu.

So anyway, recently I have also wanted to use CSS to highlight the active or current page the user is on using CSS, this is easy to do when the menu is on each page, but requires a little PHP when using a single menu included across your site.

So anyway here is my solution:

Here is the code for the navigation menu – I save this as a file called menu.php

<?php
$active[$current] = “class=active”;
?>

<ul>
<li <?php echo $active[1] ?>><a href=”index.php”>Home</a></li>
<li <?php echo $active[2] ?>><a href=”services.php”>services</a></li>
<li <?php echo $active[3] ?>><a href=”print.php”>print</a></li>
<li <?php echo $active[4] ?>><a href=”web.php”>web</a></li>
<li <?php echo $active[5] ?>><a href=”marketing.php”>marketing</a></li>
<li <?php echo $active[6] ?>><a href=”portfolio.php”>Portfolio</a></li>
<li <?php echo $active[7] ?>><a href=”contact.php”>Contact</a></li>
</ul>

Then, just include the menu on your pages and indicate which of the menu links you want to give the CSS style “active”:

<?php $current = 3; include(“menu.php”); ?>

Lastly, don’t forget to declare a visual style for the css class “active” to make the current page link stand out from the others.

VARIATION – You can also change the menu code slightly to make the active page not linkable at all – this will further make the current page stand out from the other menu options. Here is an example of the code you would use for the links:

<li <?php echo $active[1] ?>><?php if ($current != 1) { echo “<a href=\”index.php\”>home</a>”; } else { echo “home”; } ?></li>
<li <?php echo $active[2] ?>><?php if ($current != 2) { echo “<a href=\”web.php\”>web</a>”; } else { echo “web”; } ?></li>

Comments 2 Comments »