1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

How To: Alternating Your Post Background Colors

Feb 29 2008

Category: Themes and Tricks

Download | Demo

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.

<?php
$x=0;
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 ){?>
</div>
<?php }?>

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

<?php
$x++;
endwhile; ?>

Thanks for sharing this trick David!

Enjoy writing about WordPress? Get yourself more exposure by joining the Hack WordPress writing team!

Digg This Post! | Stumble This Post! | Add this Post to Del.icio.us | Google Bookmark This Post! | Netscape it! | No comment

Hack WordPress © 2008


Related Articles at Hack WordPress:


Read it at the source

Leave a Reply