Hello, my name is Pieter!

I build web applications and craft user interfaces.

Zebra striped table with CSS3

Zebra striped tables are the way to make tables with a lot of data a little more readable. You probably know this from Itunes: first song has a pastel blue background color, the second one has a white background, third has the pastel blue again, and so on...

When trying to recreate this effect on a website, you had two choices:

  1. Hardcode the classes 'odd' and 'even' and style these. When displaying tables with a lot of rows, that's not a good method.
  2. Javascript could do the trick. But a pure CSS solutions is much cleaner, isn't it?

CSS3 has a pseudo-class that is very handy for zebra tables called :nth-child(). This has a build in parameter for ‘odd’ and ‘even’.
So this is basically the same: :nth-child(odd) = :nth-child(2n+1)
:nth-child(even) = :nth-child(2n)

Click here to read more about the :nth-child() pseudo-class.

We can use these pseudo-classes on tr, and then we’ve got the zebra stripes!

First, set up a basic table: <table>
<thead>
<th>Band</th>
<th>Song title</th>
</thead>
<tbody>
<tr>
<td>The album leaf</td>
<td>Always for you</td>
</tr>
<!-- more content -->
</tbody>
</table>

Now, add some CSS with the :nth-child() pseudo-class that we’ve talked about earlier. tr:nth-child(even) { background: rgba(0, 135, 255, 0.1); }
tr:nth-child(odd) { background: #fafafa; }

As you see, it’s a pretty small piece of code. But if you run this in your browser, there’s some whitespace between the table cells. Doesn’t look that great, does it? There’s an easy fix for this: table { border-collapse: collapse; }

I’ve added some extra code that highlights the row when you hover it. This is easy too, thanks to the :hover pseudoclass. tr:hover { background: #fc6; }

That’s it, we have a working example now! I’ve added some additional styling and take a look at the demo for the final result.