29

#MyTable tr+tr:hover {
  background: #dfdfdf;
}
<table id="myTable">
  <tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2</td>
    <td>X</td>
  </tr>
  <tr>
    <td>3</td>
    <td>4</td>
    <td>X</td>
  </tr>
</table>

I managed to hover row 2 and 3 but while hover on 2 and 3, how can I skip the td (X). Preferable not using jQuery selector.

Nemus
  • 3,879
  • 12
  • 38
  • 57
Gian
  • 666
  • 4
  • 13
  • 20

4 Answers4

57

Use the :not(), :first-child and :last-child.

#myTable tr:not(:first-child):hover td:not(:last-child) {
      background: #dfdfdf;
}

Also see this example.

scessor
  • 15,995
  • 4
  • 43
  • 54
  • `:not` doesn't work until IE 9 sadly. http://www.quirksmode.org/css/contents.html, then again neither do `:last-child` nor `:first-child`... – tkone Feb 20 '12 at 14:41
3

If you're looking to not apply something to the first and last children, you can use the :first-child and :last-child selectors to override the styles.

#MyTable tr, tr:hover { 
    background: #dfdfdf;
}

#MyTable tr:first-child, tr:last-child {
    background: #000;
}

This won't work in IE until IE 9 though.

Unless you shim in some support.

tkone
  • 22,092
  • 5
  • 54
  • 78
2

I found this SO link because I did not want my header row to highlight when I hovered over it. The solution I came up with was to use <thead> and <tbody> tags and apply css to the rows within <tbody>.

<style>
    .report tbody tr:hover {
        background-color: khaki;
    }
</style>

<table class="report">
    <thead>
        <tr>
            <th>Header</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Value</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>Total</td>
        </tr>
    </tfoot>
</table>
Pete
  • 2,393
  • 2
  • 24
  • 31
1

:not(:first-child) and :not(:last-child) should do the trick, it seems those are supported by all latest browser. If you need IE<9 support you can add classes, or replace td's with th's

ЫъГЬ
  • 31
  • 1
  • 6