InternotesSharing Web Development Techniques


Zebra-Striped Tables

Posted on Tuesday, 4th June 2013 by admin

HTML tables, when correctly used, can contain many rows and columns of data. If the table is large enough, designers often wish to highlight rows to make them easier to read.

Tables with alternating shading or colouring are sometimes referred to as zebra tables, for what should be the obvious reason. HTML does not of itself support this, but this is typically achieved through classes.

Before you embark on trying to implement zebra striping, you might like to read the following article:

The gist of it is that that Zebra Tables offer no significant readability advantage over non-zebra tables, though most users agree they look better.

Typically, you create Zebra Tables this way:

    <tr class="oddrow"> … </tr>
    <tr class="evenrow"> … </tr>

In my opinion, doing this sort of thing by hand is a waste of time, given that there is no usable benefit.


If you really want to Zebra stripe your table, you can do the following in PHP:

    //Suppose rows are in an array $rows
    foreach($rows as $row) {
        $class = ++$i%2 ? 'oddrow' : 'evenrow';
        $tbody[]="<tr class="$class"> … </tr>";

    <?php print $tbody; ?>

Roughly, the variable $i is incremented, and then tested for odd or even by finding its modulus 2 value; 1, a non-zero value tests as true, while 0 tests as false.


When you use classes for alternative rows, you are defeating the purpose of symantic HTML. Classing a row simply to produce a colour is cumbersome and encodes the appearance rather than the role or meaning of the data.

There is a pure CSS solution, but it is relatively new, as part of the CSS3 specification. As a result, Certain Browsers1, you can guess which ones, do not yet support it. However, it is harmless, and it doesn’t hurt to implement it and wait for the browsers to catch up:

<!-- HTML
    ================================================ -->
    <table id="zebra"><tr> ... </tr><tr> ... </tr>...
/*  css
    ================================================ */
    table#zebra>tbody>tr:nth-child(odd)   { background-color: #f8f8f8; }
    table#zebra>tbody>tr:nth-child(even)  { background-color: #c0c0c0; }

Apart from giving the table an id – and wouldn’t you do that anyway? – this requires nothing of the table itself, and so is completely unobtrusive.

Here is a sample table which should work in all current browsers:



  1. Not IE<9, of course.