HTML table highlight row on hover except first row (header)

Andez picture Andez · Aug 9, 2012 · Viewed 82.3k times · Source

All,

I have an ASP.NET GridView that is rendered to an HTML table.

<table>
    <tr><th>Col 1 Head</th><th>Col 2 Head</th></tr>
    <tr><td>Data 1</td><td>Data 2</td></tr>
    <tr><td>Data 3</td><td>Data 4</td></tr>
</table>

I want to highlight the row when the mouse is hovered over it - except for the first row which is the header.

I am just getting my head wet with JQuery, and have dabbled a bit with CSS (either CSS2 or CSS3). Is there a preferred way to do this?

Can anyone give me a starting point for this?

Cheers

Andez

Answer

Chris picture Chris · Aug 10, 2012

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!