All Posts by Email, Once a Week

Media Temple logo

CSS-Tricks is brought to you in part by Media Temple, the web hosting that we both use and recommend.

Alternate table row colors

  • # February 1, 2010 at 7:41 pm


    I would like to find a function that alternates a table’s row colors in PHP. I used to have one but I can’t find the file anymore.

    Thanks guys!

    # February 2, 2010 at 12:45 am

    Even included a table header spot if you want.
    table-heading – Styles for the table header.
    odd – Styles for the odd rows.
    even – Styles for the even rows.

    $(document).ready(function() {
    # February 3, 2010 at 1:04 am

    You could consider using the jquery solution suggested by noahgelman. if you really want / need a php solution it depends on the source of your table-data. if you are iterating over the data (like an array) the solution could be:

    echo ‘
    $counter = 1;
    foreach($foo as $bar){
    $class = “odd”;
    if($counter % 2 == 0) $class = “even”;
    echo ‘

    echo ‘

    ‘ . $bar . ‘


    # February 12, 2010 at 3:54 pm

    What about nth child(even)?

    EDIT: I suppose if you wanted a PHP solution (dirtying your markup!) you could do something like:

    for( $n = 0; $n < $size; $n++ ) { if ($n % 2) echo ' class="evenrow"'; else echo ' class="oddrow"'; }

    Fill that in with your other stuff too (database reads and writes and such) but there’s your basic structure.

    Although I still like the purely CSS solution better.

# February 16, 2010 at 2:30 am


there are snippets for a solution in both jQuery and PHP

Viewing 5 posts - 1 through 5 (of 5 total)

You must be logged in to reply to this topic.

There's a whole bunch of content on CSS-Tricks.

Search for Stuff   •   Browse the Archives

Get the Newsletter ... or get the RSS feed