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 background color rotates every other row.
Does that make sense? Thanks!
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 ?>">
...
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With