JPS
JPS

Reputation: 2760

tr:hover & tr:nth-child(odd ~ even) does not work together

I wanted to highlight the table row on hover. So I've used the following CSS rule,

.my-table tbody tr:hover{
  background-color: #BFC0C2;
}

It worked well alone. Later I've included the CSS rule to make the different background color for odd and even rows of the table,

.my-table tbody tr:nth-child(odd){
  background: #FFFFFF;
}
.my-table tbody tr:nth-child(even){
  background: #f2f2f3;
}

Now the odd and even rows are having differnt background color But on hover the row is not getting highlighted. Can't I use both of them together? Here is the plunker.

Upvotes: 1

Views: 4634

Answers (4)

Paulie_D
Paulie_D

Reputation: 115098

This is a specificity / cascade issue.

Either re-order the CSS

td {
  padding: 10px;
  border: 1px solid grey;
}
.table tbody tr:nth-child(odd) {
  background: #FF0000;
}
.table tbody tr:nth-child(even) {
  background: green;
}
.table tbody tr:hover {
  background: grey;
}
<table class="table">
  <tbody>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

OR increase the specifity of the hover in the same way

td {
  padding: 10px;
  border: 1px solid grey;
}
.table tbody tr:nth-child(n):hover {
  background-color: #BFC0C2;
}
.table tbody tr:nth-child(odd) {
  background: #FF0000;
}
.table tbody tr:nth-child(even) {
  background: green;
}
<table class="table">
  <tbody>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>

Upvotes: 4

aarcangeli
aarcangeli

Reputation: 331

You can also change td's background

  .my-table tbody tr:hover td {
    background-color: #BFC0C2;
  }
  .my-table tbody tr:nth-child(odd) {
    background: #FFFFFF;
  }
  .my-table tbody tr:nth-child(even) {
    background: #f2f2f3;
  }

Upvotes: 2

JoannaFalkowska
JoannaFalkowska

Reputation: 3677

Examining in the browser you can see that both selectors apply, but one is overridden:

enter image description here

Just place it earlier in code or add !important and it'll work fine.

Upvotes: 0

Hassan Nisar Khan
Hassan Nisar Khan

Reputation: 312

its just the matter of specificity of the selector, increase it my any mean will solve the problem example

.my-table tbody tr:hover {
    background-color: #BFC0C2 !important;
} 

Upvotes: 1

Related Questions