Examples for Alternating Table Row Colors

' ASP Version
strsql = "SELECT Adjective, Noun FROM DrSeussLines"
objRS.Open strsql,objCN,adOpenForwardOnly,adLockReadOnly,adCmdText
i = 0
Response.write "<table>"
Do While Not objRS.EOF
i = i + 1
Response.write "<tr class=""d" & (i And 1) & """>"
Response.write "<td>" & objRS(0) & "</td>"
Response.write "<td>" & objRS(1) & "</td>"
Response.write "</tr>" & vbCrLf
objRS.MoveNext
Loop
objRS.Close
Response.write "</table>"

// PHP Version
$query = "SELECT Adjective, Noun FROM DrSeussLines";
$result = mysql_query($query);
$i = 0;
print "<table>";
while(($row = mysql_fetch_row($result)) !== false) {
$i++;
print "<tr class=\"d".($i & 1)."\">";
print "<td>".$row[0]."</td>";
print "<td>".$row[1]."</td>";
print "</tr>\n";
}
mysql_free_result($result);
print "</table>";

For non-DB pages

Efficient Alternating Table Row Colors

To produce the same effect with less code, instead define two types of TR classes. Then, use inheritance to the TD tag. Read the example and the explanation will follow.

<style type="text/css">
tr.d0 td {
background-color: #CC9999; color: black;
}
tr.d1 td {
background-color: #9999CC; color: black;
}
</style>
<table>
<tr class="d0"><td>One</td><td>Fish</td></tr>
<tr class="d1"><td>Two</td><td>Fish</td></tr>
<tr class="d0"><td>Red</td><td>Fish</td></tr>
<tr class="d1"><td>Blue</td><td>Fish</td></tr>

0 comments:

Post a Comment