Fun CSS Tricks: the nth-child Selector

Posted on June 14th, 2011 by Chris

Rabbit in a HatAs we wrap up the final few bugs fixes and feature additions that we want to have ready before BlogShouts goes live this month, I ran into a minor bit of CSS/JavaScript wackiness that was annoying me. I wanted alternating “Shout Cards” to have different margin widths, but I didn’t want Gabe to have to write a bunch of code to spit out Shout Cards with alternating classes. My initial solution was to use a jQuery routine to add a CSS class to every second Shout Card on the page so that it wouldn’t inherit the margin that I had declared for Shout Cards in general.

This bit of JavaScript I used was really simple, and looked like this:

$("article.shout:even").addClass("left");

There are two problems with this approach: for one thing, it’s simply less-elegant than a CSS-only approach. For another thing, the more AJAX you start doing on a page, the more you run into weird issues where the even Shout Cards forget their margins and start bouncing all over the page, especially in Internet Explorer 9. No good.

This is where the nth-child CSS Selector comes in really handy. Using it, you can selectively apply styles to only particular instances of a set of elements, even when they all have the same class. So I removed my jQuery line, and instead of adding a class to every other object via JavaScript, I simply used the following CSS:

#bsContent .shout {
    margin:0 5px 25px 5px; padding:11px;
    border:3px solid #CCC;
    background:#FFF;
}
    #bsContent .shout:nth-child(even) {
        margin-right:25px;
    }

I’ve bolded the really important line, there, down at the bottom. What this is saying is: for every even instance of the .shout class (starting at 0), add a 25-pixel right margin. You could do odd numbers by replacing “even” with “odd”, and you can specify other sequences by using something like nth-child(9n) — which would apply to every ninth item, or even nth-child(5n-2) – which would highlight the 3rd, 8th, and so forth items. For a more complete explanation of how nth-child works, take a look over at this CSS Tricks page.

This child selector works in all modern browsers, and some older non-IE browsers. To get it working in IE8 or below, you will need to play around with some jQuery, but it should still give a more robust experience than the method described at the beginning of the post.

Happy scripting!

Leave a Response