Reputation: 14511
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!
Upvotes: 6
Views: 42580
Reputation: 357
For have a small php inside your html you can use
<?php echo ($striped)?'even':'odd';$striped=!$striped;?>
use alternate between even and odd.
Upvotes: 1
Reputation: 31
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;
}
Upvotes: 3
Reputation: 21
i guess the best option is to use the internal iterator of foreach :
example :
<table>
<?php foreach ($foo as $key => &$bar) : ?>
<tr class="<?php echo ($key + 1) % 2 ? 'odd' : 'even'; ?>">
<td> ... </td>
</tr>
<?php endforeach; ?>
</table>
Upvotes: 2
Reputation: 54022
this is My way, you can try this
<style type="text/css">
.even{
background-color:#333;
}
.odd{
background-color:#666;
}
</style>
<?php
$i=0;
foreach( ... ){
++$i;
?>
<tr class="<?php echo ($i%2) ? 'even' : 'odd' ?>">
<td>..</td>
</tr>
<?php } ?>
...
Upvotes: 1
Reputation: 4920
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 } >
Upvotes: 0
Reputation: 14205
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; }
Upvotes: 21
Reputation: 382736
You can do something like this:
$counter = 0;
while(............){
$counter++;
$bgcolor = ($counter % 2 === 0) ? 'red' : 'blue';
}
Now you can use bgcolor="<?php echo $bgcolor;?>"
for your TDs
:)
Note that above will work in all browsers including IE6.
Upvotes: 3
Reputation: 138082
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
<!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>
Upvotes: 6
Reputation: 4323
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 ?>">
...
Upvotes: 11