I have a table that is dynamically generated by PHP. I am hoping that I can use CSS to apply a background color based on where the table row is odd/even, i.e. the backgroun
In CSS define the below class
.color0 { #fff; }
.color1 { #ccc; }
In PHP Code use the below technique
while($row=mysql_fetch_assoc($q))
{
echo "<tr class='color$c'>";
echo "<td>data</td>";
echo "</tr>\n";
$c=!$c;
}
You can use the nth-of-type() or nth-child() selector in CSS3. Supported by all modern Browsers.
For example...
tr:nth-child(odd) { background-color: #ccc; }
/* Do this… */
tr:nth-of-type(odd) { background-color: #ccc; }
/* …or this */
tr:nth-of-type(even) { background-color: #ccc; }
Try this :
css:
.row0{
background:white;
}
.row1{
background:black;
}
in php while printing rows (trs)
<?php
$i = 0;
foreach( ... ){
$i = 1-$i;
$class = "row$i";
?>
<tr class="<?php echo $class ?>">
...
just do like this
$codd[0] = 'even';
$codd[1] = 'odd';
$codd_i = 1;
foreach($items as $item){
$codd_i = ($codd_i+1)%2;
?>
<tr class="<?php echo $codd[$codd_i] ?>">
</tr>
<?php } >
In theory it's as easy as tr:nth-child(even) { background: #999; }
However, support for nth-child isn't amazing and will only work on the newest browsers
Example:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>
<title>Test</title>
<style type="text/css">
thead, tr:nth-child(even) { background: #aaa; }
</style>
</head>
<body>
<table>
<thead>
<tr><th>Header</th><th>Header</th></tr>
</thead>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
<tr><td>Data</td><td>Data</td></tr>
</table>
</body>
</html>
For have a small php inside your html you can use
<?php echo ($striped)?'even':'odd';$striped=!$striped;?>
use alternate between even and odd.