How To Create Zebra Striped Tables

Photo of Mike Dalisay
Modified Sunday, October 10, 2010
by - @ninjazhai
Zebra striped tables look good. It guides the user's eyes when looking into your rows of data. This one useful when you have long list of data, making your app more user friendly.

How To Create Zebra Striped Tables
Zebra Striped Table


Step 1: Prepare your database configuration file. (I have config_open_db.php). As for the table structure, we can have the following:
CREATE TABLE `users` (
   `id` int(11) not null auto_increment,
   `firstname` varchar(32) not null,
   `lastname` varchar(32) not null,
   `email` varchar(32),
   `username` varchar(32) not null,
   `password` varchar(32) not null,
   PRIMARY KEY (`id`)

Step 2: Create styles folder and inside it is the style.css file. We will have this code:

th {
    padding: 5px;
    background-color: #999999;

td {
    padding: 5px;

.odd-row {
    background-color: #E3E3E3;

.even-row {
    background-color: #D1D1D1;
Step 3: Create index.php file, inside the index.php file, you should have these codes:

    <title>How To Create Zebra Striped Table</title>
    <link href='styles/style.css' type='text/css' rel='stylesheet' />
//to be connected to the database
include 'config_open_db.php'; 

//query your data
$sql = 'select * from users';
$rs = mysql_query ( $sql );

echo "<table border='0' cellpadding = '2'>";
echo "<tr>"; // Create the table headings
    echo "<th>Firstname</th>";
    echo "<th>Lastname</th>";
    echo "<th>Email</th>";
    echo "<th>Username</th>";
echo "</tr>";

//Set the background color of your first row

while ( $row = mysql_fetch_array( $rs ) ){

    //this is the condition on what will be the bg color of a row
    //at the same time, changing the value of $bg for the next loop
    //in this way, our table will have alternate row color
    //that makes it "Zebra Striped"
    if( $bg == 1){
        echo "<tr class='odd-row'>";
        echo "<tr class='even-row'>";
    echo "<td>{$row['firstname']}</td>";
    echo "<td>{$row ['lastname']}</td>";
    echo "<td>{$row['email']}</td>";
    echo "<td>{$row['username']}</td>";
    echo "</tr>";

echo "</table>";


I have a follow up post for this one: How To Highlight Table Row OnMouseOver

For FREE programming tutorials, click the red button below and subscribe! :)
Thanks for the comments!
"First do it, then do it right, then do it better."
~ Addy Osmani
"Talk is cheap. Show me the code."
~ Linus Torvalds
Let's Stay Connected!
g+ r
Android app on Google Play
© 2011-2014 The Code Of A Ninja. All rights reserved. Proudly Powered by Google Blogger. Images, logos, marks or names mentioned herein are the property of their respective owners.