Reputation: 23
Does anyone know how to have different colours on alternate rows in a table
Upvotes: 1
Views: 2678
Reputation: 23556
http://www.w3.org/Style/Examples/007/evenodd
table.evenodd tr:nth-child(even) { background: #CCC; }
table.evenodd tr:nth-child(odd) { background: #FFF; }
Upvotes: 4
Reputation: 10781
Typically I would have an even
and odd
css class that defined the different colours then in PHP when outputting the <tr>
I would apply this to the element. You'd typically use a row counter in your loop and mod2 the counter.
$rows = 0;
while ($row = mysql_fetch_array($result)) {
$rows++;
$even_odd = ($rows % 2) ? 'odd' : 'even' ;
echo "<tr class=$even_odd><td>";
echo "<center>" .$row['name']. "</center>";
echo "</td><td>"
echo "<center>" .$row['age']. "</center>";
echo "</td><td>"
echo "<center>" .$row['car']. "</center>";
echo "</td></tr>"
}
Upvotes: -1
Reputation: 7539
You can use jquery to add classes to the rows like this:
<script type="text/javascript">
$(document).ready(function () {
$("table.evenodd tr:not([th]):odd").addClass("odd");
$("table.evenodd tr:not([th]):even").addClass("even");
});
</script>
And then use CSS to style:
.even {background-color: #e6e6e6;}
.odd {background-color: #ffffff;}
Upvotes: 5
Reputation: 8101
You need to apply a style to every second row. You can do that by adding a counter to your loop, and if that counter-variable % 2 == 0
, you add the style to the row in question, like this:
$i = 0;
while ($row = mysql_fetch_array($result)){
$style = "";
if($i%2==0)
{
$style = ' style="background-color: #CCC"';
}
echo "<tr".$style."><td>";
echo "<center>" .$row['name']. "</center>";
echo "</td><td>"
echo "<center>" .$row['age']. "</center>";
echo "</td><td>"
echo "<center>" .$row['car']. "</center>";
echo "</td></tr>"
$i++;
}
Upvotes: 0