Change background of second last item in a nav

How can I change the second last item on the below Navigation bar item to different color. in the below example I need to change the color of Contact background to a different color.

There are multiple ways to do it… You can simply put a class on the link and then style based on the class. You can use :nth-child(5) like…

.nav ul li:nth-child(5) > a {
  background-color: blue;

But usually the best way to do it is just attach a CSS class to the element you want to stylize. For instance like create a style rule named “.active” and then attach it to whatever link you want to be stylized with that class. This is how it is usually done with scripts and such that can assign the class based on some query selector.

Btw, the nth-child example should work as I have tried it with your pen. But I know the class method will definitely work as that is how I typically do it.


Thank you very much, it worked.
As you said I’ll try by adding a class.

I’ve added a class to that li item and added background-color to that class but color showing in drop down also

You seem to have added it the class to the anchor in the codepen and not the list item? You would still need to target the anchor from the new list class.

In your current version you need to match the specificity of the original rules rather than using !important.


.nav .blue{
  background-color: blue;

You will almost never need to use !important as that is a lazy hack in most cases.

1 Like

Hi there viveknath322,

you can, of course, do second last item without magic numbers. :winky:

	color: #00f;


MDN - :nth-last-child()