Alternating Your Post Background Colors

May 12, 2008 · Print This Article

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; ?>

Your choice for site templates and wordpress themes


Got something to say?

You must be logged in to post a comment.