Sunday, January 25, 2009

Alternating table row colors

Here is a nice simple way of alternating table row colours.
The example is shown in PHP but the principal can be applied in any language.

Step 1 : First I create a very simple style for each row.
<style type=”text/css”>
.row1 { background: #000; color: #fff; }
.row0 { background: #fff; color: #000;}
</style>
Step 2 : Now I create a simple loop that prints my rows
<?php
print '<table>';
#Start at 0
$row = 0;
for ( $counter = 0; $counter <= 5; $counter ++)
{
$row = 1 - $row;
#Now I print the row with it’s css class name ‘row1' or 'row0′
print "<tr class=\"row$row\"><td>Row $row</td></tr>\n";
}
print '</table>';
?>

Source Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Colour Change sample</title>
<style type="text/css">
.row1 { background: #000; color: #fff; }
.row0 { background: #fff; color: #000;}
</style>
</head>
<body>
<?php
print '<table>';
#Start at 0
$row = 0;
for ( $counter = 0; $counter <= 5; $counter ++)
{
$row = 1 - $row;
#Now I print the row with it’s css class name ‘row1' or 'row0′
print "<tr class=\"row$row\"><td>Row $row</td></tr>\n";
}
print '</table>';
?>
</body>
</html>