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.

Leave a Comment

* Name, Email, Comment are Required