9

I am trying to create a table that has a rowspan, zebra effect and highlights the row on hover. I kind of got it working but not quite.

It should be like this: http://codepen.io/chriscoyier/pen/wLGDz plus a zebra effect on the rows. Unfortunately a zebra effect using jQuery or CSS does not work for me as the lines won't change on hover if I do that.

Any suggestions?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
rhslogic
  • 339
  • 2
  • 5
  • 9
  • You could use Bootstrap as it all comes built in with it: http://twitter.github.com/bootstrap/base-css.html#tables – Billy Moat Mar 17 '13 at 18:57

2 Answers2

52

This is a job for tbody. Multiple tbody elements are allowed in a table at least as far back as HTML4, and they're designed for grouping related rows together. This way, you don't need JavaScript at all.

body {
  padding: 1em;
}

table {
  width: 100%;
  border-collapse: collapse;
}

td,
th {
  padding: .25em;
  border: 1px solid black;
}

tbody:nth-child(odd) {
  background: #CCC;
}

tbody:hover td[rowspan],
tr:hover td {
  background: red;
}
<table>
  <tbody>
    <tr>
      <td rowspan="3"></td>
      <td>a</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>b</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>c</td>
      <td></td>
      <td></td>
    </tr>
  </tbody>

  <tbody>
    <tr>
      <td rowspan="3"></td>
      <td>a</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>b</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>c</td>
      <td></td>
      <td></td>
    </tr>
  </tbody>

  <tbody>
    <tr>
      <td rowspan="3"></td>
      <td>a</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>b</td>
      <td></td>
      <td></td>
    </tr>
    <tr>
      <td>c</td>
      <td></td>
      <td></td>
    </tr>
  </tbody>
</table>
RCRalph
  • 355
  • 6
  • 17
cimmanon
  • 67,211
  • 17
  • 165
  • 171
-2

Something like:

// stripe
tr:nth-child(even) {
    background-color: #ccc;
}
// hover
tr:hover {
     background-color: #c00;
}

should work. Post your code up.

Bob
  • 177
  • 1
  • 3
  • 11