Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to make a striped table

Short answer

Shade every second row with the :nth-child(even) selector:

<style>
  table { border-collapse: collapse; }
  th, td { padding: 6px 12px; text-align: left; }
  tbody tr:nth-child(even) { background: whitesmoke; }
</style>
 
<table>
  <thead><tr><th>Product</th><th>Price</th></tr></thead>
  <tbody>
    <tr><td>Tea</td><td>$3</td></tr>
    <tr><td>Coffee</td><td>$5</td></tr>
    <tr><td>Juice</td><td>$2</td></tr>
    <tr><td>Water</td><td>$1</td></tr>
  </tbody>
</table>

even means even rows, odd — odd ones. The selector starts with tbody so the header row does not count.

Other alternations

A formula can go inside the :nth-child() brackets. 3n selects every third row, 4n + 1 — the first of every four. This is how stripes are made in groups, for example by weeks in a schedule.

A highlight on hover

In a wide table the eye easily slips to a neighboring row. A highlight under the pointer helps:

<style>
  table { border-collapse: collapse; }
  td { padding: 6px 12px; }
  tr:nth-child(even) { background: whitesmoke; }
  tr:hover { background: lightyellow; }
</style>
 
<table>
  <tr><td>Anna</td><td>Design</td><td>$25</td></tr>
  <tr><td>Oleg</td><td>Code</td><td>$30</td></tr>
  <tr><td>Maria</td><td>Tests</td><td>$20</td></tr>
</table>

Common mistake

Stripes are set by hand with class="odd" in every row. Once a row is removed or added, the alternation breaks — two gray rows in a row. :nth-child recounts the rows by itself.

Functions used in this recipe

  • :nth-child() — Matches children by their position: the third, every even one, every third one.
  • <table> — A table made of rows (`<tr>`) and cells.
  • <thead>, <tbody>, <tfoot> — Groups of table rows: the head, the body and the footer.
  • :hover — Matches an element while the mouse pointer is over it.
  • background-color — The background color of an element.

Thanks for reading!

Donate to the site — we work hard for you.