Tag Archives: CSS Inline

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.

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

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 ?