Zebra Tables

Derek Jones edited this page Jul 5, 2012 · 15 revisions
Clone this wiki locally


Community: Please feel free to add other methods :-)

Zebra tables is a term used to describe tables that have alternating row colours:


This effect can be achieved using various methods, both server and client-side using PHP and CSS/Javascript.

Basic method


.tr1 td{ background:#F4B624; color:#000; }
.tr2 td{ background:#FFFFFF; color:#000; }


Make sure the string helper is loaded. It contains a function called alternator(), which is exactly what we need here. This function allows two or more items to be alternated between when cycling through a loop.

<?php foreach ($result as $row) { ?>

<tr class="tr&lt;?php echo alternator('1', '2') ?&gt;">
  <td>&lt;?php echo $row->name ?&gt;</td>
  <td>&lt;?php echo $row->descriptions ?&gt;</td>

&lt;?php } ?&gt;


<tr class="tr1">

<tr class="tr2">

Table Class Method

This method uses CodeIgniter's built-in table class library. First, build an array with the data for the table:

    array('Number in Stock','Item Name'),
    array('98','Sheets of Paper'),

Then build an array with some table settings:

    'table_open' => '<table class="zebraTable">',
    'row_start' => '<tr class="rowOdd">',
    'row_alt_start' => '<tr class="rowEven">'

This sets an opening class for all your odd rows, and all your even rows, and cleans up the table opening tag. Only a class is really needed, if you're going for XHTML.

Build the table into a variable to pass to your View:

$this->table->set_template($table_settings); //apply the settings
$data['table'] = $this->table->generate($this->foo->getFoo()); //build the html output and stick in our data array

Use the following (or similar!) styles in whichever stylesheet you wish to use:

.zebraTable tr {
.zebraTable .rowEven {

The resulting table html code is something similar to:

<table class="zebraTable">
<th>Number in Stock</th><th>Item Name</th></tr>
<tr class="rowOdd">
<tr class="rowEven">

<tr class="rowOdd">
<td>98</td><td>Sheets of Paper</td></tr>
<tr class="rowEven">

Good luck, and have fun!