Keeping it Small and Simple

2007.06.02

Alternating row color in HTML/CSS (with PHP)

Filed under: CSS, HTML, PHP Programming — Lorenzo E. Danielsson @ 00:28

I frequently get asked how to create an HTML in which the rows have alternating background color. Most of the people who ask me this are PHP programmers or at least striving to be, so I’m going to use PHP for the example, but the principle is of course valid regardless of implementation language.

First of all, create two CSS classes, row0 and row1. Set the background-color of each to be a different value. Here is an example:

.row0 {
    background-color: #ffffff;
}

.row1 {
    background-color: #f0f0f0;
}

You will probably be creating your table rows inside a loop of some form. You will need to have flag that will hold either 0 or 1, depending on the CSS class to use for the current table row. How do we make sure that the value is always 0 or 1? Simple. Assuming the name of our flag variable is $rowclass then we just do:


$rowclass = 1 - $rowclass;

Since this will evaluate to 0 if $rowclass is 1, or 1 if $rowclass is 0 it does exactly what we want. I think it is easier to understand how it works if you see it used. So take a look at the following:

<html>
<head>
<title>Table example</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
<table>
<tr>
<th>Toon</th>
</tr>

<?php
$toons = array("Bugs Bunny", "Daffy Duck", "Tom Cat", "Jerry Mouse");
$rowclass = 0;
foreach ($toons as $toon) {
?>
    <tr class="row<?= $rowclass ?>">
    <td><?= $toon ?></td>
    </tr>
<?php
    $rowclass = 1 - $rowclass;
} ?>

This assumes that you called your stylesheet file style.css and placed it in the same directory as the php file. If you did that you should see a table with four rows, where rows one and three have a white background and rows two and four have a light gray background.

This simple example iterates through the array $toons, but you could do the same thing if your data is the result of a database query.

While we’re at it, I also get asked how to make the rows change background color when the mouse moves over them. That isn’t difficult either. Just add the following to your stylesheet:

.row0 {
    background-color: #ffffff;
}

tr.row0:hover {
    background-color: #ffff00;
}

.row1 {
    background-color: #f0f0f0;
}

tr.row1:hover {
    background-color: #ffff00;
}

Adding the :hover part specifies the style to apply when the mouse is over a table row. This is frequently used to style hyper-links, but it can be used for table rows as well.

Advertisements

Blog at WordPress.com.