Last Updated: September 09, 2019
·
4.126K
· corysimmons

Easy nth-child fallback with iteration

I've seen a lot of, "How do I apply a class of foo to every third blog post?"

And a lot of people replying, "Just use nth-child".

Well, nth-child doesn't work in IE8 and below. That's a pretty big chunk of people.

So, use nth-child, but also use iteration. Here's a quick example of how to do this in WordPress' Loop:

<?
    $i = 1;
    if ( have_posts() ) : while ( have_posts() ) : the_post();
    $i++;
?>
    <article<? if($i % 3 == 0) { echo ' class="last"'; } ?>>
        <header><? the_title(); ?></header>
        <? the_excerpt(); ?>
    </article>
<? endwhile; else: ?>
    <p><? _e('Sorry, no posts matched your criteria.'); ?></p>
<? endif; ?>

Breakdown

  1. We declare $i = 1
  2. Then we say, "Start fetching posts"
  3. As soon as you have the first post loaded, add one to whatever $i is
  4. Then we go into our actual markup and say, "If $i is divisible by 3 then..."

In things like Django this is trivial with the divisibleby template tag, but using this concept is cross-browser and cross-language. Enjoy.

3 Responses
Add your response

À bit (in my opinion) cleaner solution might be to print <?php echo ($i++ % 3 === 0) ? "class=last" : ""; ?> Also it's good practice to use triple "=" in this case just to make sure that the comparison is 0 and not NULL or FALSE.

over 1 year ago ·

Sorry for the late response, but thank you. I'll use this implementation in the future. :)

over 1 year ago ·

What would you do if you wanted a bit more complex version like every 5th, 8th, 11th post should have a class applied to it? These aren't divisible by the same number apart from 1.

over 1 year ago ·