Skip to main content

Displaying data in HTML tables is great as it provides clear structure and allows users to easily read what you’re telling them. But it sometimes gets hard to determine between different rows and columns. Adding borders can help, but it just doesn’t look clean. Using alternating CSS row colors, or CSS Zebra Striping can easily solve this.

In this brief article I’m going to show you how to use both CSS Zebra Striping and PHP alternating row colors. Personally I think CSS is the way to go, but some still prefer to use PHP to achieve this.

CSS Alternating Row Colors

CSS 3 brought with it a bunch of new features, two of those being nth-of-type or nth-child. Both can be used in this context to achieve the same goal. Combining these new functions with odd or even, we can easily alternate/zebra stripe the table rows.

[css]
table tr:nth-of-type(odd) {
background-color: #aaa;
}

table tr:nth-child(odd) {
background-color: #aaa;
}
[/css]

This is a very simple solution to an old problem with web design. You don’t even need to specify the background color for other rows.

PHP Alternating Row Colors

To alternate rows in PHP you need to use PHP math to work out when a row is divisible by two.

The PHP method is typically used as a fallback on legacy websites that won’t be utilising multiple stylesheets for different devices. This is because the PHP method hardcodes a CSS class into the HTML, making the server do the work, in contrast to CSS which makes the end user’s browser do the work.

[php]
$i = 0;
?>
<tr class="<?=($i++%2==1) ? ‘odd’ : ”; ?>">
[/php]

Then you need to also define the CSS like so –

[css]
table tr.odd {
background-color: #aaa;
}
[/css]

As you can see, the PHP method requires a much larger amount of code, which as you increase the number of tables used on your website will increase the amount of code exponentially.

Why is CSS the better solution?

The primary role of CSS is to determine how the web page is displayed. The primary role of PHP is to determine what is displayed. If you want to build a website for multiple devices in different views then you need to use CSS to display things differently, but if you’ve hardcoded display styles in with PHP then this will prove much more difficult.

Conclusion

This simple tutorial has taken you through the two easy ways to alternate row colors in both PHP and CSS. You now understand when to use each solution and why PHP should only be the fallback when CSS doesn’t cut it.

Subscribe for Updates

Get notified about my latest content first and receive invitations for subscriber only competitions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.