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
- We declare $i = 1
- Then we say, "Start fetching posts"
- As soon as you have the first post loaded, add one to whatever $i is
- 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.
Written by Cory Simmons
Related protips
3 Responses
À 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.
Sorry for the late response, but thank you. I'll use this implementation in the future. :)
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.