How To Create Zebra Striped Tables

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
DOWNLOAD SOURCE CODE LIVE DEMO

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:

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:

<html>
    <head>
    <title>How To Create Zebra Striped Table</title>
    <link href='styles/style.css' type='text/css' rel='stylesheet' />
    </head>
<body>
<?php
//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
$bg=1; 
 
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'>";
        $bg=2;
    }else{
        echo "<tr class='even-row'>";
        $bg=1;
    }
     
    echo "<td>{$row['firstname']}</td>";
    echo "<td>{$row ['lastname']}</td>";
    echo "<td>{$row['email']}</td>";
    echo "<td>{$row['username']}</td>";
    echo "</tr>";
     
}
 
echo "</table>";
?>
 
</body>
</html>

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

By Mike Dalisay

I'm Mike Dalisay, a pro web developer since 2010. I love web development. Improving our tutorials and source codes makes me happy. Do you want to suggest an edit to our tutorial? Got something to ask about our source codes? Email our team at [email protected]