Three ways to alternate row colors in a table

When creating an HTML table, it is often a good idea to alternate the color of the rows and make the data more readable.

The best, in our opinion, is through CSS rules:

tr:nth-child(odd) { 
    background-color:#FFC600; 
}
tr:nth-child(even) { 
    background-color:#FFFFFF; 
}

Alternatively you can do this with a server-side language, for example in PHP:

<?php

for ($i = 0; $i < count($allmyrows); $i++) {
 
    if ($i % 2 == 0) {
        $color = '#FFC600';
    }
    else {
        $color = '#FFFFFF'; 
    }

    echo "<tr style='background-color: " . $color . ";'>";
    echo "<td>" . $allmyrows[$i] . "</td>";
    echo "</tr>"; 

}

Or client side with jQuery:

$(document).ready(function() {
      
    $('tr:odd').css('background-color', '#FFC600');
    $('tr:even').css('background-color', '#FFFFFF');
      
});

Leave a Comment

Your email address will not be published. Required fields are marked *