Zebra striping a table with hidden rows using CSS3?

Viewed 22280

I've got a table

<table id="mytable">
    <tr style="display: none;"><td>&nbsp;</td></tr>
    <tr><td>&nbsp;</td></tr>
    <tr style="display: none;"><td>&nbsp;</td></tr>
    <tr><td>&nbsp;</td></tr>
    <tr><td>&nbsp;</td></tr>
    <tr><td>&nbsp;</td></tr>
 </table>

I'm trying to set the table striping to use nth-child selectors but just can't seem to crack it.

 table #mytable tr[@display=block]:nth-child(odd) { 
      background-color:  #000;  
 }
 table #mytable tr[@display=block]:nth-child(odd) { 
      background-color:  #FFF;
 }

I'm pretty sure I'm close ... can't quite seem to crack it.

anyone pass along a clue?

11 Answers

If anyone tries to do something like me, where I have alternating hidden and visible rows, you can do this:

.table-striped tbody tr:nth-child(4n + 1) {
background-color: rgba(0,0,0,.05);
}

This will get every 4th element starting with the 1st one, and allows you to maintain striping with hidden rows between each visible row.

Here is a 2022 version of a javascript version

let cnt = 0;
document.querySelectorAll("#mytable tbody tr").forEach(tr => {
  cnt += tr.hidden ? 0 : 1;
  tr.classList.toggle("odd",cnt%2===0); 
});
.odd { background-color: grey; }
<table id="mytable">
<thead><tr><th>Num</th></tr></thead>
  <tbody>
    <tr><td>1</td></tr>
    <tr><td>2</td></tr>
    <tr><td>3</td></tr>
    <tr hidden><td></td></tr>
    <tr><td>5</td></tr>
    <tr><td>6</td></tr>
  </tbody>  
</table>

Related