How To: Alternating Your Post Background Colors

Comments Off on How To: Alternating Your Post Background Colors

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!

  • Leave a Comment