View Full Version : Table repeat region and applying alternate background colors.

01-31-2008, 03:58 AM
When you create a dynamic table is there a way to apply alternate colors to the rows? Say header row blue then the dynamic rows odd light gray and the even rows white etc?

01-31-2008, 05:50 AM
how are your coding skills??

01-31-2008, 06:00 AM
wrap your chops round this

its my own monster



$no = 1; //<< set start counter

do { //<< start loop

$divide = $no / 2; //<< divide by 2 which will turn odd numbers into floats

//<< set boolean $detect using string search.
//Search for decimal in float.
//If found you have detected odd numeric.
$detect = strstr($divide,'.');

//check the IF statement in <tr> to echo the appropriate class
//if $detect is true then that is odd so echo color1 else echo color2

<tr <?php if($detect){echo "class=\"color1\"";}else{echo "class=\"color2\"";} ?>>
<td><?php echo $row['field1_id'];?></td>

<td><?php echo $row['field2'];?></td>

<td><?php echo $row['field3'];?></td>

<td><?php echo $row['field4'];?></td>


$no++; //<< increment count.

}while ($row = mysql_fetch_array($result))



02-01-2008, 02:26 AM
Thanks davidj,

here's another option using JS.

in the <head> place:

function alternate(id){
var table = document.getElementById(id);
var rows = table.getElementsByTagName("tr");
for(i = 0; i < rows.length; i++){
//manipulate rows
if(i % 2 == 0){
rows[i].className = "even";
rows[i].className = "odd";

Then at the first<body> and <table> type:

<body onload="alternate('thetable')">
<table id="thetable">
Now if you use dreamweaver like me to make your dynamic tables (getting better at coding one day I'll do it myself) change the first row <td> to <th> this will allow you to apply a css style to the table header making different from the white and gray.

08-23-2010, 04:22 AM
Thanks a bunch davidj

I modified your code a bit to fit my foreach needs.

Here's how I did it:


$no = 1; //<< set start counter

<?php foreach($news as $new): ?>
<?php $divide = $no / 2; $detect = strstr($divide,'.'); ?>
<tr <?php if($detect){echo 'class="rowcolor1"';}else{echo 'class="rowcolor2"';} ?>>
<div id="text">
<?php echo($new['text']); ?>

I simply set .rowcolor2 to a light gray and .rowcolor1 to "background: none"

Works beautifully!

08-23-2010, 09:40 AM

That was an old post

Pleased its still helping!