Skip to main content
Participating Frequently
July 9, 2009
Answered

alternate row colours in dynamic tables?

  • July 9, 2009
  • 2 replies
  • 743 views

Hi all,

I know that alternate row colors are easily accomplished on static tables using class styles. Does any one know if this can be implemented on pages that dynamically display multiple records?

This topic has been closed for replies.
Correct answer David_Powers

Yes, it's very easy to do. The actual coding depends on your server-side language. The basic principle is to use the modulo operator (%) with a counter that's incremented with each iteration of the loop.

Modulo division produces the remainder of a division sum. So, if you use modulo division on the counter, and divide the counter by 2, the result will alternate between 1 and 0, which can be used to determine which class to apply to the current row.

In PHP:

<?php $i = 0;

<?php do {

<tr <?php if($i++ % 2) {echo 'class="hilite"';} ?>>

<!-- rest of code -->

</tr>

<?php } while ($row_recordsetName = mysql_fetch_array($recordsetName)); ?>

Create a style rule for all table rows, and a different one for the hilite class. Stripes.

2 replies

David_Powers
David_PowersCorrect answer
Inspiring
July 9, 2009

Yes, it's very easy to do. The actual coding depends on your server-side language. The basic principle is to use the modulo operator (%) with a counter that's incremented with each iteration of the loop.

Modulo division produces the remainder of a division sum. So, if you use modulo division on the counter, and divide the counter by 2, the result will alternate between 1 and 0, which can be used to determine which class to apply to the current row.

In PHP:

<?php $i = 0;

<?php do {

<tr <?php if($i++ % 2) {echo 'class="hilite"';} ?>>

<!-- rest of code -->

</tr>

<?php } while ($row_recordsetName = mysql_fetch_array($recordsetName)); ?>

Create a style rule for all table rows, and a different one for the hilite class. Stripes.

Participating Frequently
July 9, 2009

Thank you so much.

David_Powers
Inspiring
July 9, 2009