Skip to content Skip to sidebar Skip to footer

Adding Php Alternate Table Row Colours To Existing Html Table

I have a Table already written in PHP that echos out data called from the database like so:

Solution 1:

You could use the following when looping through the results returned from your db:

<?php// Define row colors$color1 = "#FFFFFF";
$color2 = "#F4F9FF";

// Set row counter$row_count = 0;

while ($row = mssql_fetch_array($result)) {
    $row_color = ($row_count % 2) ? $color1 : $color2;
?><trbgcolor="<?phpecho$row_color; ?>"><tdalign="center"><?phpecho$row["PageURL"]; ?></td><tdalign="center"><ahref="PageUpdate.php?id=<?phpecho$row["PageID"]; ?>"><imgsrc="images/0013-pen.gif"width="16"height="16"alt=""border="0"></a>&nbsp;&nbsp;&nbsp;</td></tr><?php$row_count++;

}

?>

Alternatively, you could replace the bgcolor tags and assign a CSS class to each row.

Solution 2:

Use the CSS selector :nth-of-type( ).

By putting different styles for both the :nth-of-type(even) and :nth-of-type(odd) the browser does the alternating styling for you, so you won't have to worry about it.

See the W3Schools entry on this.

Solution 3:

Try This:

<tr<?phpif($i%2){?>bgcolor="#eeeeee"<?php } else{ ?>bgcolor="red"<?php } $i++; ?>>

Solution 4:

Thanks to Bas van den Heuvel for the great answer using CSS. If you encountered extra line spacing like I did, and want to remove it, use the following example code. This will make the alternating color lines be tighter together. (I used light grey and white)

p:nth-of-type(odd)
{
background:#e2e2e2;
margin: 0px;
padding: 0px;
}
p:nth-of-type(even)
{
background:#ffffff;
margin: 0px;
padding: 0px;
}

Post a Comment for "Adding Php Alternate Table Row Colours To Existing Html Table"