Highlighting the current page that is being viewed in a navigation bar is a popular design choice for many websites. The CSS is easy: make a class for the navigational element that represents the current page in a linked stylesheet:
a.current {
background: black;
color: white;
}
Then apply the class to the appropriate element for the current page. Using the previous exercise as an example:
<nav role="navigation">
<a href=index.php>Home</a>
<a href="about.php">About Us</a>
<a href="popular-routes-to-india.php" class="current?">Popular Routes To India</a>
<a href="prices.php">Prices</a>
</nav>
At first glance, this would imply that taking the design option of highlighting the current page would stymie our goal of having a single include
, or at least set it back: we’d now have to make the navigation code unique to every page in order to insert the .current
class into the appropriate link for each page. That means more work for us, and greater chances of mistakes and inconsistencies in content.
However, with PHP, we do know the name of the page we are currently on: in the last exercise, we have that information contained in the PHP constant title
. In that case, we can keep our single include()
, and make the application of the .current
class dynamic in pagestart.php. For each link, we simply have to see if we are on the appropriate page that matches the link, and apply the .current
class if we are. (For clarity, only two of the navigational list items are shown below, with sections of code placed on separate lines to enhance readability).
<a href="about-us.php" class=<?php if (title=="About Us") echo "current"; ?>">About Us</a>
<a href="popular-routes-to-india.php" class="<?php if (title=="Popular Routes To India") { echo "current"; } ?>">
Popular Routes To India</a>
If we are not on a page that matches title
, the link class
will be set to ""
, which is valid; if we are on a page that matches, class
will be set to current
and the appropriate CSS will be applied to the link.
Once you know the PHP to produce it, making navigation that is “self-aware” is easy. Adding new links to the navigation bar is as simple as working out the appropriate title
value for the associated filename and placing the if
statement for the link.
Enjoy this piece? I invite you to follow me at twitter.com/dudleystorey to learn more.