Before advanced CSS selectors became widely supported in browsers, it was necessary to use JavaScript to automatically add stripes or zebra stripes to HTML tables. You can also manually add classes to zebra stripe a table. But both of those methods are suboptimal.
Assuming HTML code that looks like this:
<table>
<thead>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<th>Col 4</th>
<th>Col 5</th>
<th>Col 6</th>
<th>Col 7</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<!-- rest of the code here... -->
</tbody>
</table>
Code language: HTML, XML (xml)
You can stripe all rows in such a table using the following CSS:
/* can also be "even" */
tbody tr:nth-child(odd) {
background-color: lightpink;
}
Code language: CSS (css)
Using tbody
in the selector ensures that the th
row is not considered in the zebra striping. The :nth-child
pseudo-class allows you to use the keywords odd
or even
to easily zebra stripe every other row. See the demo below.