Zebra striping makes tables easier to scan by giving alternating rows different background colors. With modern CSS selectors, adding stripes is quick and straightforward. In this article, I’ll show you how to create zebra-striped tables using only CSS.
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.