AKor
AKor

Reputation: 8882

Alternating table row background colors on a dynamic table

I have a table generated by a foreach loop.

Before the loop, I create $iteration = 0. At the beginning of the loop it increments $iteration.

Then I do this:

if($iteration % 2 == 0) { 
  $greyRow = 'css for a grey row'; 
}

I've only three rows, at max, to test this with, but it seems that it greys the 2nd and 3rd row under the current rule, rather than only the second.

Upvotes: 0

Views: 1959

Answers (3)

Jim Rubenstein
Jim Rubenstein

Reputation: 6920

I like to do this kind of thing..

<style type="text/css">
.odd td { background: #eee; }
</style>
<tr class="<?= ++$iteration % 2? 'odd' : 'even'; ?>">....</tr>

Upvotes: 2

Jason McCreary
Jason McCreary

Reputation: 72971

This following will add a grey class for even rows.

echo '<tr', ($iteration & 1 ? ' class="grey"': ''), '>';

Note

This uses a bitwise operator. It's a micro-optimization but far more optimal than the modulus operator (although notoriously used in these cases).

Also, I would encourage you to utilize CSS classes for even and odd rows versus inline styles or just toggling a single class (i.e. grey).

echo '<tr class="', ($iteration & 1 ? 'even': 'odd'), '">';

Upvotes: 4

mellamokb
mellamokb

Reputation: 56769

Perhaps you also need to have an else statement to set back to the other color on the odd rows. Not quite sure without seeing more of your implementation.

if ($iteration % 2 == 0) {
    $css = 'css for a grey row';
} else {
    $css = 'css for a white row';
}

Upvotes: 2

Related Questions