o_O
o_O

Reputation: 5737

How to get tr:nth-of-type(odd) for entire table not group (thead, tbody)?

Using CSS I set the zebra-striping background color for tables using tr:nth-of-type(odd). Of course, this is the first child of parent. Is there a way to specify this is the index for the table instead of the parent groups? For example, here is the outcome:

tr:nth-of-type(odd) { background: blue; }
<table>
  <thead>
    <tr>Blue
    <tr>
    <tr>Blue
  </thead>
  <tbody>
    <tr>Blue
    <tr>
    <tr>Blue
  </tbody>
  <tfoot>
    <tr>Blue
  </tfoot>
</table>

What I would like:

tr:nth-of-type(odd) { background: blue; }
<table>
  <thead>
    <tr>Blue
    <tr>
    <tr>Blue
  </thead>
  <tbody>
    <tr>
    <tr>Blue
    <tr>
  </tbody>
  <tfoot>
    <tr>Blue
  </tfoot>
</table>

Pictures for posterity:

enter image description here

Upvotes: 2

Views: 1312

Answers (1)

Douglas Denhartog
Douglas Denhartog

Reputation: 2054

I'm not aware of how to do this using 100% CSS :/

BUT! Of course you don't have to use thead/tfoot as the only required element is tbody ;)

SO, this JSFiddle is has the row coloring you want!

You could class the faux thead/tfoot rows in a class if you like :)

<table>
  <tbody>
    <tr><th>faux thead blue</th></tr>
    <tr><th>faux thead not</th></tr>
    <tr><th>faux thead blue</th></tr>
    <tr><td>not</td></tr>
    <tr><td>Blue</td></tr>
    <tr><td>not</td></tr>
    <tr><th>faux tfoot blue</th></tr>
    <tr><th>faux tfoot not</th></tr>
    <tr><th>faux tfoot blue</th></tr>
  </tbody>
</table>

But in case you HAVE to use thead/tfoot, you could use the preceding, er, *cough* following *cough* jQuery/JS:

$("table").each(function(){ $(this).find("tr:even").css('background', '#e1e9f0'); });

Upvotes: 1

Related Questions