Alternate Background Color of Blog Posts

As my tag pages grow I have been contemplating how I wanted to handle their appearance. The goal is to have as many post excerpts as possible on each tag page while creating a page that is easy to read. I decided to try something a little different that I have not seen on too many blogs, actually, I am not sure I have seen it at all except on some comments, which is alternating the background color of each post.

So, how hard would this be?

It took about an hour to get it the way I wanted it. I am alternating the background color and the Adsense ads on each tag page. A good example is the Google Tag Page since it has a lot of posts.

Rotate Background

Here is a summary of how I did this:

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

Not sure if anyone else likes this style, but it sure seems to make the excerpts easier to read for me. Please let me know what you think ?

15 thoughts on “Alternate Background Color of Blog Posts

  1. @Kyle, Thanks, like you posted on your site, there are lots of places where a loop occurs in WP and the same idea can be applied.

  2. I used this with blueprint CSS to append the “last” on alternating posts. The result is a wonderful grid of posts. It worked ravishingly. Thanks!

  3. Christian,

    Interesting idea, I just had to test it. Since the default order is newest post first, you can just loop through starting at the first post.

    Here is the working code to change colors for 5 posts on a page.

    Color posts by date

    The first post stays your default color, then it starts fading grey, it could be expanded and improved, I just spent a few minutes to test it.

  4. David, you rock!

    The code works perfect! I changed the styling to suit my needs but other than that it is spot on.

    Just threw a cup of coffee your way via PayPal.

    Thanks for the help and the speed at which it was provided.

  5. Again, thanks for the help. Works like a champ. Still some tweaking and browser testing/adjusting to work on but thought I’d at least show it off.

    I wrote a quick note about the process on the 19th but plan to do a better one in the next couple of days. I’ll make sure to give credit where it is due.

Leave a Reply

Your email address will not be published. Required fields are marked *