Verbose Logging

software development with some really amazing hair

T + G I F R

Making nth-child Work Everywhere

· · Posted in Programming
Tagged with

The nth-child pseudo selector is a nice feature in CSS3. Well, most of the things in CSS3 are pretty sweet.

Chris Wanstrath has a good post on the nth-child selector, and I'd suggest reading it for a bit more in depth on what the nth-child selector actually does, as I just cover getting the same effect in all browsers.

Unfortunately, while Internet Explorer does support some of the CSS3 stuff, it doesn't support a bunch of them.aspx) either. (Disclaimer: I am considering IE 7 and 8. IE6 isn't a real web browser…)

The nth-child selector is one of them.

Basically then nth-child selector allows you to do stuff like this in CSS3:

table.highlight tr:nth-child(2n+1)

This will select all the odd rows in the table. You can then give them a different background color, to make the table easier to read. Like I said, good thing Internet Explorer supports it.

jQuery to the rescue!

The nice thing about jQuery is that it does support nth-child and it's completely cross browser compatible (read: works in Internet Explorer).

Now you can change your CSS rule to something poor IE can understand:

table.highlight tr.odd

Top it off with some jQuery sauce…

$('table.highlight tr:nth-child(2n+1)').addClass('odd');

Now you have the same effect. In all browsers. Win.