Advertisement
CSS

Alternating Row Colors in CSS and PHP

Post image

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.

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

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

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' : ''; ?>">

Then you need to also define the CSS like so -

table tr.odd {
	background-color: #aaa;
}

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.

Advertisement
You may also like:
comments powered by Disqus