Pseudo Class 'nth-child()' not working with ':hover"

Viewed 343

I'm trying to use the pseudo class :nth-child() with :hover but it seems to not work for me. I am trying to change the colour of one element to green when hovered over, but it highlights all of them. I also tried without the hover and none of the colours change.

ul {
    background-color: white;
    text-decoration: none;
    padding: 0;
    margin: 0 auto;
}
ul li {
    margin: 0 2em;
    display: inline-block;
    padding: 0;
    list-style: none;
}
ul li a {
    text-decoration: none;
    color: black;
}
a:nth-child(2){
color: green;
}
<ul>
      <li><a href="#">Easy</a></li>
      <li><a href="#">Medium</a></li>
      <li><a href="#">Hard</a></li>
      <li><a href="#">Insane</a></li>
</ul>

2 Answers

That's because the a isn't the 2nd child - it is an only child of it's parent li. What you are looking for is the a child of the 2nd li element. You can get that like this:

li:nth-child(2) a{ color: green; }

Then for the hover, either of these work with the code in your question. It depends on what you want to target with the hover:

// When the <a> in the second li is hovered, change it's colour
li:nth-child(2) a:hover{ color: green; }

/* OR */ 

/* When the second li is hovered, change the colour of the <a> it contains */
li:nth-child(2):hover a{ color: green; }

Working Example (using different colours to show it working):

ul {
    background-color: white;
    text-decoration: none;
    padding: 0;
    margin: 0 auto;
}
ul li {
    margin: 0 2em;
    display: inline-block;
    padding: 0;
    list-style: none;
}
ul li a {
    text-decoration: none;
    color: black;
}

/* change colour of 2nd link */
li:nth-child(2) a{
    color: blue;
}

/* change colour of 2nd link on hover */
li:nth-child(2):hover a{
    color: green;
}

/* change colour of 3rd link on hover */
li:nth-child(3) a:hover{
    color: red;
}
<ul>
      <li><a href="#">Easy</a></li>
      <li><a href="#">Medium</a></li>
      <li><a href="#">Hard</a></li>
      <li><a href="#">Insane</a></li>
</ul>

Reference: Mozilla MDN Docs for nth-child

Related