Grow your CSS skills. Land your dream job.

Alternate table row colors

  • # February 1, 2010 at 7:41 pm

    Hey!

    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.

    Code:
    $(document).ready(function() {
    $(‘th’).addClass(‘table-heading’);
    $(‘tr:not([th]):odd’).addClass(‘odd’);
    $(‘tr:not([th]):even’).addClass(‘even’);
    });
    # 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:

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

    ‘;
    $counter++;
    }
    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:

    Code:
    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

UUUUUUUMMMMMMMM

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.

*May or may not contain any actual "CSS" or "Tricks".