Reputation: 9
this is my code for a multiplication table. By combining PHP and HTML/CSS I need to make every alternating rows background color white or grey.
I've thought of using a row and using %2==1 and %2==0 to
figure out the odd and even rows but how would i target those rows to make a id or class to target on my css file?
Where would I insert this code at?
<?php
echo '<table>';
echo '<tr><th></th>';
for ($x = 1; $x <= 9; $x++)
echo '<th>'.$x.'</th>';
echo '</tr>';
for ($y = 1; $y <= 9; $y++)
{
echo '<tr><th>'.$y.'</th>';
for ($z = 1; $z <= 9; $z++)
{
echo '<td>'.($y * $z).'</td>';
}
echo '</tr>';
}
echo '</table>';
?>
Upvotes: 0
Views: 924
Reputation: 10190
No need to assign classes with PHP when CSS can style alternate elements just fine. Using nth-child
you can style alternative rows pretty easily.
tr:nth-child(even) {
background: #f5f5f5;
}
tr:nth-child(odd) {
background: #ddd;
}
Here is a fiddle showing it off: Fiddle
And here is more info on the nth-child
selector: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
Upvotes: 2
Reputation: 15922
As Dryden Long comments, best is CSS, but if you do need do it with php, you could do:
<?php
echo '<table>';
echo '<tr><th></th>';
for ($x = 1; $x <= 9; $x++)
echo '<th>'.$x.'</th>';
echo '</tr>';
for ($y = 1; $y <= 9; $y++)
{
echo '<tr class="'. ( ($y%2 == 0 ) ? 'even' : 'odd' ).'"><th>'.$y.'</th>';
for ($z = 1; $z <= 9; $z++)
{
echo '<td>'.($y * $z).'</td>';
}
echo '</tr>';
}
echo '</table>';
and then you only have to add the CSS classes, and all will be working.
table tr.even { background-color: blue }
table tr.odd { background-color: red }
Upvotes: 0
Reputation: 4194
echo '<tr class ="' . ( $y % 2 == 0 ? 'even' : 'odd' ) . '"><th>'.$y.'</th>';
You can use the ternary operator to insert a class
condition ? if true : if false;
Upvotes: 0