1. Technology

How to Make a Zebra Striped Table with CSS 3

Using nth-of-type(N) with Tables

By

Pattern of black and white lines
Rian Hughes/Stockbyte/Getty Images

One of the most common ways to style tables is to set the background color of every other row. This is often refered to as "zebra stripes". This type of striping makes the table much easier to read. But it requires that you add a class to every other table row and then set styles for them.

This works fine, but every time you need to edit that table, you may have to edit every single row in the table to get the classes correct. For example, if you add a new row to your table, every other row below it needs to have the class changed.

But CSS 3 makes it easy to style tables with zebra stripes. You don't need to add any extra HTML attributes or CSS classes, you just use the nth-of-type CSS pseudo-class.

Write Your HTML Table

First write your table as you would normally write it in HTML. Don't add any special classes to the rows or columns.

<table>
  <tr>
    <td>test test test</td>
    <td>test test test</td>
    <td>test test test</td>
    <td>test test test</td>
  </tr>
  <tr>
    <td>test test test</td>
    <td>test test test</td>
    <td>test test test</td>
    <td>test test test</td>
  </tr>
  <tr>
    <td>test test test</td>
    <td>test test test</td>
    <td>test test test</td>
    <td>test test test</td>
  </tr>
  <tr>
    <td>test test test</td>
    <td>test test test</td>
    <td>test test test</td>
    <td>test test test</td>
  </tr>
  <tr>
    <td>test test test</td>
    <td>test test test</td>
    <td>test test test</td>
    <td>test test test</td>
  </tr>
</table>

Then Add the CSS Pseudo-Class

In your style sheet, add the following CSS:

tr:nth-of-type(odd) {
  background-color:#ccc;
}

This will style every other row with a gray background color starting with the first row.

See the zebra striped table.

You Can Also Style Every Other Column in the Same Way

Instead of tr, change your style to td. For example:

td:nth-of-type(odd) {
  background-color:#ccc;
}

See the zebra striped columns.

©2014 About.com. All rights reserved.