Zebra Stripe Tables – Alternating Row Colors
Recently I received the following question:
Currently i’m working on a table within css and am trying to create a table with related data, separated by different colored backgrounds. A lot like many programs that host information in rows. Where I am failing, is the positioning of the data within that zebra table through CSS. Can you give a brief description, or a description in full, how I could create this?
The general concept of accomplishing this is pretty simple. You are going to be needing 2 different css classes, which you can find examples of below. It works using inheritance from the row instead of applying the styles to every single table cell.
tr.even td {
background-color: #FFF;
color: #000;
}
tr.odd td {
background-color: #F5F5F5;
color: #000;
}
The css classes will be taking care of the actual look and feel of the zebra stripe. The trick is going to be getting the styles on the proper rows. The best approach would be to do it on the server side. A common method is to use a counter and use modulus to find out whether or not the row is even. If there isn’t a remainder, that means the row is even!.
for ($i=0; $i<10; $i++) {print “<tr class=’”. $i % 2 == 0 ? “even” : “odd” .”‘>”;print “<td>Stripe</td>”;print “</tr>\n”;}
The above is a relatively brief description, if you would like more detail. Feel free to leave comments and I will be glad to add more!