Different color for each menu item in WordPress

In a recent project, I got a requirement that each menu item should be highlighted in a different color when visited. The menu items and their required active colors were:

  • Home – Green
  • Portfolio – Blue
  • Team – Yellow
  • Contact – Red

These colors were to be applied only when that page is being visited otherwise color of the menu item should be the default black color.

So, if a user is visiting the home page then the menu item should something like this

home_menu.png

And if the user is visiting the Portfolio page then the menu should be something like this

portoflio_menu.png

Considering that this was a WordPress theme project where we were using Understrap as a base theme which is based on Twitter Bootstrap. So, when user visits, for example, a home page WordPress will attach a .active CSS class to it. Taking advantage of that we added different classes for each menu item and then used the following rule to make menu item colors different:

.navbar-nav > .home.active > a {
    color: green!important;
}
.navbar-nav > .portfolio.active > a {
    color: blue!important;
}
.navbar-nav > .team.active > a {
    color: yellow!important;
}
.navbar-nav > .connect.active > a {
    color: red!important;
}

CSS Class Chaining Method

We utilized the class chaining method here. If you note that .home.active classes are chained together without space and which means it will select an element with both these classes.
That did the trick and all menu items were in a different color.
Share your love
Muhammad Jawaid Shamshad
Muhammad Jawaid Shamshad
Articles: 128

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.