One thing I’ve always loved to do is set up my blogs comments to display alternating background colors (although ironically I have not done so for this site yet). I’ve always felt that this helps give the comments a little more separation from each other and improve the overall look of the blog.

Because WordPress is full of loops (homepage, category, tag, etc.), this same theory can truly be applied all over your blog. David of CyberCoder posted yesterday a great hack to alternate the background of your blog posts. Here are the steps you need to take:

Create a loop counter. Right before the Loop begins set a variable to zero.

if (have_posts()) : ?>

At this point I would want the Background Color to change, insert code to test for an even number post, and if this is true, add an inline CSS style for the background that would override the stylesheet.

<?php if ($odd = $x%2){?>
<div style=”background-color:#404040;padding:10px 0px 10px 10px;”>
<?php }?>

Then, where the background color should return to the original state, run the same test for the even numbered post and close the div tag set by the Inline Style.

<?php if( $odd = $x%2 ){?>
<?php }?>

The final step is to add 1 to the counter for each post, which is done at the end of the loop.

endwhile; ?>

Thanks for sharing this trick David!

Kyle Eslick is WordPress enthusiast who took his passion for WordPress to the next level in 2007 by launching as a place to share hacks, tutorials, etc. Follow Kyle on Twitter @KyleEslick!

Trackbacks/Pingbacks »

  1. 100+ Killer Wordpress Resources | Steffan Antonas’ Blog says:
  2. displaying alternating different backgroung color | Pligg CMS Forum says: