How to: Alternate background color in comments list

If you have a large amount of comments on your blog, it can be very more readable to alternate background colors. In this recipe, I’m going to show you how to do it easily.

Edit the comments.php file from your theme. First, find the following line:

<?php if ( $comments ) : ?>

Once you found it, replace the comment loop by the following code:

<ul>
<?php $i = 0; ?>
<?php foreach ($comments as $comment) : ?>
    <?php $i++; ?>
    <li id="comment-<?php comment_ID() ?>"
    <?php if($i&1) {
        echo 'class="odd"';
    } else {
        echo 'class="even"';
    } ?>>
<php endforeach; ?>
&lt/ul>

The above code automatically ad a css class to each comment. You guessed it, we now have to edit style.css and create two nice styles for our comments.
You can use this code, for exemple:

.odd {
    background-color: #fcf9fc;
}

.even {
    background-color: #616161;
}

That's all, your comments now appears with alternated background colors. Nice, isn't it?

Credits goes to WordPress Garage for this awesome recipe!

Related Posts

Related Posts

No related posts.

9 Responses

Nov 09 2008 22:37

Hi Jean,

This is another nice tutorial! I’ll implement it to my upcoming blog… not all of my blogs have a lot of “commenters” lol.

Regards,
Tyrone

Nov 09 2008 23:33

This will probably not have to be done if you have a WP 2.7+ comment structure.

Nov 10 2008 00:05

@Joost de Valk: Thanks for the info! I can’t wait for WP 2.7. But many themes aren’t optimized for WP 2.7 yet, so this recipe can still be usefull I think.

Have a nice evening :)

Nov 29 2008 04:45

Doesn’t help me… Rather, it shows “class=”even”" and “class=”odd” at the top of each comment.

Dec 27 2008 05:35

Nice job. But doesn´t work for me :(
Bad luck!!

Maxi Sanchez

Trackbacks:

Leave a Comment

* Name, Email, Comment are Required