Code Newbie
News     Forums     Search     Members     Sign Up    

My Code Newbie
Username

Password

Articles/Snippets
ASP Classic
ASP.NET
C
C#
C++
HTML / CSS
Java
Javascript
Linux / BSD
Perl
PHP
Python
Ruby
SQL
VB 6
VB.NET

C.N. Friends
  Planet Rome

Link to Us!
Code Newbie
  Code Newbie
    php
  » Alternating Table Row Background Colors
      by sde
 Page 1 of 1 
   

(Login to remove green text ads)
In this tutorial, you will learn how to make background colors of table rows alternate with a simple math equation.

Alternating background colors for a table with many rows helps the user follow information across the table easier, and quite possibly might make your site look a little more professional. In this example, I will use the variable $num to define how many rows will be in this table. I'm setting it to 20, but this of course can be determined by a mysql_numrows() function after requesting data from MySQL.
PHP Code:
<?
$num
=20;
Now that I know the value of $num, I can start my loop. $i is the number of the row and it will increase by 1 for each new row printed.
PHP Code:
// Open the HTML table before the loop
echo "<table border=0 cellspacing=0 cellpadding=0>";

// define the loop parameters and start loop
for($i=0;$i<$num;$i++){ 
Now for the magic! The theory here is that for every even numbered row ($i), the background will print the first color, and every odd numbered row will print the second color.
PHP Code:
// define which colors for even and odd line numbers
  
if($i ==0)
  {
    
$bgcolor='#f3f3f3';
  } 
  else 
  {
    
$bgcolor='#e3e3e3';
  }

  
// echo the table content with $bgcolor
  
echo "<tr bgcolor=$bgcolor><td> This is line number $i </td></tr>";

// close loop
}

// close table
echo "</table>";
?> 
You should now be able to see your alternating background colors!

( Thanks Vivo for the Corrections! )




 
 Page 1 of 1 
   

Rate This Article
1 2 3 4 5 6 7 8 9 10





Copyright © 2000-2006, Milano Interactive
Web Hosting provided by Portal 360 Web Hosting
Open Circle