CSS Highlight Current Link

When using a php include for your menu having it so the current page link is highlighted isn’t as easy to do as it would be if the menu is coded onto each page. There are a few solutions to achieve this, such as using php as shown in the A List Apart’s article Keeping Navigation Current With PHP, or using one of the many JavaScript solutions. But this can also be achieved using CSS and HTML with no other scripting language needed.

Step One – The HTML

Within the navigation menu add a class to each of the links in your menu:

<ul>
<li><a href="home.htm" class="home">Home</a></li>
<li><a href="about.htm" class="about">About</a></li>
<li><a href="contact.htm" class="contact">Contact</a></li>
</ul>

Step Two – The CSS

If you are wanting the highlights to share the same style you can simply list them together by separating each class with a comma, like so:

body.home a.home, body.about a.about, body.contact a.contact {
    background-color: #000000;
}

If you want them to have different styles then simply create a separate class for each.

Step Three – Body Class

Finally in each of the pages you need to tell it which class it needs to pay attention to so that the highlight will work. To do this simply add the class into the body tag like this:

<body class="home">

There you have it, a simple solution to creating an active state for pages when you cannot do it manually.

7
Comments

  • November 7, 2009 | Permalink |

    Great short tutorial. I’ve used this before but you’ve simplified it down a lot, thanks!

  • November 26, 2009 | Permalink |

    I’m ashamed to say but this is one thing I’ve never thought of and never known how to use! I’ve finally been able to apply it to be a website that I’m doing too! So that’s great!!!

    Thanks so much

  • Dizi
    November 26, 2009 | Permalink |

    Luke I’m glad that this tutorial has been of use and taught you a new technique :)

  • DPdesign
    June 12, 2010 | Permalink |

    Neat trick, thanks for sharing

  • September 8, 2010 | Permalink |

    This is much easier than how I have been doing it.

    Thanx for the easy to follow tutorial.

  • Dan
    October 26, 2010 | Permalink |

    I always use php for this as it doesn’t produce as much code and means that a class is only used when needed rather than having redundant ones.

  • November 16, 2010 | Permalink |

    Interesting and different than how I’m doing it, will try it from now on, thanks alot!

Have Your Say

Your email is never shared. Required fields are marked *
To add code to a comment use this [code] your code here [/code]