HTML table highlight row on hover except first row (header)
There is a way to achieve the desired behavior without class-ing each row separately. Here's how to highlight each table row except for first one (header) on hover using the CSS :not
and :first-child
selectors:
tr:not(:first-child):hover {
background-color: red;
}
Unfortunately, IE < 9 does not support :not
, so to do this in a cross-browser way, you can use something like this:
tr:hover {
background-color: red;
}
tr:first-child:hover {
background-color: white;
}
Basically, the first CSS rule includes all rows. To avoid highlighting the first row, you override the its hover style by selecting with tr:first-child
and then keeping its background-color
to white (or whatever the non-highlighted row's color is).
I hope that helped, too!
To expand on user2458978's answer surely the best way of doing this is to code up the tables correctly.
<table>
<thead>
<tr><th></th></tr>
</thead>
<tbody>
<tr><td></td></tr>
<tr><td></td></tr>
</tbody>
</table>
Then the CSS is simply
table tbody tr:hover { background-color: red; }
Here's a jsFiddle example
You can do this using the CSS :hover
specifier. Here's a demonstration:
<table>
<tr><th>Col 1 Head</th><th>Col 2 Head</th></tr>
<tr class = "notfirst"><td>Data 1</td><td>Data 2</td></tr>
<tr class = "notfirst"><td>Data 3</td><td>Data 4</td></tr>
</table>
CSS:
.notfirst:hover {
background-color: red;
}
1.
Place header tr inside thead tag
2.
Place other tr inside tbody tag
3.
Use following css
table tr:not(thead):hover {
background-color: #B0E2FF;
}
Use TH tag for first row and do that:
th {
background-color:#fff;
}
For all others rows:
tr:not(:first-child):hover {
background-color:#eee;
}
or
tr:hover td {
background-color:#eee;
}