PHP Zebra Striping


Alternating the colour of blocks of content (or zebra striping) can make things easy on the eyes for your website visitors and enhance their overall experience on your site.

Zebra striping may be the ideal solution for separating the comments on your blog. If you are using a PHP powered website such as Wordpress (or any other PHP powered site) this is extremely simple to implement.

Let's assume that we want to add an odd and an even CSS class to alternate comments.

Add the following code at the top of your foreach() or while() loop.

<?php $even_odd = ( 'odd' != $even_odd ) ? 'odd' : 'even'; ?>

Then where you want to output the additional classes add the following:

<?php echo $even_odd; ?>

To bring it all together in a real example here is an example of some code taken from a Wordpress comments.php file with the above concept applied:

<?php foreach ($comments as $comment) : ?>
  <?php $even_odd = ( 'odd' != $even_odd ) ? 'odd' : 'even'?>
<li id="comment-<?php comment_ID() ?>" class="<?php echo $even_odd; ?>">
<?php comment_text() ?>
<div class="comment-details"><cite><?php comment_type(__('Comment'), __('Trackback'), __('Pingback')); ?> <?php _e('by'); ?> <?php comment_author_link() ?> &#8212; <?php comment_date() ?> @ <a href="#comment-<?php comment_ID() ?>"><?php comment_time() ?></a></cite> <?php edit_comment_link(__("Edit This"), ' |'); ?></div>
<?php endforeach; ?>

I wrote a PHP class for this

I wrote a PHP class for this makes implementing it much easier:

Submitted by halogenandtoast (not verified) on Sun, 2008-07-27 12:40.

Web Hosting

It is very useful to me....Interesting Article

Submitted by Emma (not verified) on Mon, 2010-05-31 22:14.