Alternate table row colors with CSS

Hello everyone. I am styling a table and I want to have alternate row colors. I know that the obvious way to do that is to create two classes and attach the appropriate class to the row you want to change. But I want to know if there is a way to do it totally in the external sheet without adding to markup.

I was thinking that :nth-of-type(2) selecting the <tr> element would work, but that only makes the second row the alternate color right? Is there a pseudo class, or even a property that will alternate rows without adding anything to the markup?

Not sure about support, but you can use odd or even keywords in the brackets.

this should work (but not suported by <=IE8)

The following example selectors are equivalent, and will match odd-numbered table rows:

tr:nth-child(2n+1) {
⋮ declarations
}
tr:nth-child(odd) {
⋮ declarations
}

Thank you, I didn’t know about that. That’s good to know that “odd” and “even” exist for the keywords. Well, unless I can find out how to get them working for legacy browsers, I will have to wait on implementing it (once again, IE is my stumbling block :nono:). Thanks for the help.

you could also use javascript (/jQuery) to add trhe odd class to the odd rows.

look at : http://api.jquery.com/odd-selector/ (the jQuery odd selector)

or in regular JS you can for loop with step of 2 to add the class

God bless Javascript. I’ll try that out.

Update:

I realized that the Javascript I use to bring IE7+ up to code (forgive the pun) actually already fixes the lack of support for legacy browsers for not only nth-of-type but for many other handy properties and pseudo elements. It even makes HTML5 usable for basic styling in IE 7+. Now that I know about “odd” and “even” that just makes my life so much easier in updating these tables and not having to mess around with classes in the mark-up.

http://ie7-js.googlecode.com/svn/test/index.html

The only thing I notice is that for some reason, IE 7 and 8 are ignoring my selector of “tbody tr:nth-of-type(even) {}” and are applying it starting with the <tr> element in the <thead>. So, for IE 7 and 8 the first row is the colored one, and for 9 and Firefox etc, it is obeying the selector and the colored row is starting as the second as it should.

I’ll need to tweak it to figure out why.