InternotesSharing Web Development Techniques

Blossoms

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:

http://www.alistapart.com/articles/zebratables/

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:

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

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

PHP

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

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

<table>
    <?php print $tbody; ?>
</table>

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.

CSS

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>...
    </table>
/*  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:

ID Name Value
1 One Bun
2 Two Shoe
3 Three Tree
4 Four Door
5 Five Hive
6 Six Sticks
7 Seven Heaven
8 Eight Gate
9 Nine Line
10 Ten Hen

Links

www.alistapart.com/articles/zebratables/


  1. Not IE<9, of course.