Tony
Tony

Reputation: 23

Alternating colours on a dynamic table

Does anyone know how to have different colours on alternate rows in a table

Upvotes: 1

Views: 2678

Answers (4)

Hauleth
Hauleth

Reputation: 23556

http://www.w3.org/Style/Examples/007/evenodd

table.evenodd tr:nth-child(even) { background: #CCC; }
table.evenodd tr:nth-child(odd) { background: #FFF; }

Upvotes: 4

hafichuk
hafichuk

Reputation: 10781

Typically I would have an even and odd css class that defined the different colours then in PHP when outputting the <tr> I would apply this to the element. You'd typically use a row counter in your loop and mod2 the counter.

$rows = 0;
while ($row = mysql_fetch_array($result)) {
  $rows++;
  $even_odd = ($rows % 2) ? 'odd' : 'even' ;
  echo "<tr class=$even_odd><td>";  
  echo "<center>" .$row['name']. "</center>"; 
  echo "</td><td>" 
  echo "<center>" .$row['age']. "</center>"; 
  echo "</td><td>" 
  echo "<center>" .$row['car']. "</center>"; 
  echo "</td></tr>" 
}

Upvotes: -1

TheGeekYouNeed
TheGeekYouNeed

Reputation: 7539

You can use jquery to add classes to the rows like this:

<script type="text/javascript">
    $(document).ready(function () {
        $("table.evenodd tr:not([th]):odd").addClass("odd");
        $("table.evenodd tr:not([th]):even").addClass("even");
     });
</script>

And then use CSS to style:

    .even {background-color: #e6e6e6;}
    .odd {background-color: #ffffff;}

Upvotes: 5

Jan Dragsbaek
Jan Dragsbaek

Reputation: 8101

You need to apply a style to every second row. You can do that by adding a counter to your loop, and if that counter-variable % 2 == 0, you add the style to the row in question, like this:

$i = 0;
while ($row = mysql_fetch_array($result)){
    $style = "";
    if($i%2==0)
    {
        $style = ' style="background-color: #CCC"';
    }

    echo "<tr".$style."><td>";  
    echo "<center>" .$row['name']. "</center>"; 
    echo "</td><td>" 
    echo "<center>" .$row['age']. "</center>"; 
    echo "</td><td>" 
    echo "<center>" .$row['car']. "</center>"; 
    echo "</td></tr>" 
    $i++;
}

Upvotes: 0

Related Questions