Search code examples
htmlcsscss-selectorspseudo-class

Add pseudo class to nth-child with CSS


I want to use hover so that the bottom border on odd divs is a different color from #75dcff. However, .card:hover div:nth-child(odd) does not work. Can I apply psuedo classes to nth-child elements?

.card {
  margin: 30px;
  padding: 20px 40px 40px;
  max-width: 500px;
  text-align: left;
  background: #fff;
  border-bottom: 4px solid #ccc;
  border-radius: 6px;
}

.card:hover {
  border-color: #75dcff;
}

.card:hover div:nth-child(odd) {
  border-color: #ff7c5e;
}
<div class="card"></div>
<div class="card"></div>
<div class="card"></div>


Solution

  • Your selector is incorrect. .card:hover div:nth-child(odd) is selecting odd-indexed divs that are decendants of a .card, but your structure suggests that these should be the same thing. Adjust your selector to match the odd elements on hover:

    .card {
      margin: 30px;
      padding: 20px 40px 40px;
      max-width: 500px;
      text-align: left;
      background: #fff;
      border-bottom: 4px solid #ccc;
      border-radius: 6px;
    }
    
    .card:hover {
      border-color: #75dcff;
    }
    
    .card:nth-child(odd):hover {
      border-color: #ff7c5e;
    }
    <div class="card"></div>
    <div class="card"></div>
    <div class="card"></div>