This post will be more relevant in the future when more browsers support the new CSS 3 Selector specification, which includes a lot of neat attribute and pseudo-element selectors, among other things.

I’ve been looking for a way to do alternating table rows with CSS only; no JavaScript and no adding class=”alternating” to the tr element in server-side code. After a tiny bit of experimenting, I found the following solutions:

Alternating every other row:

tr:nth-child(odd) {
background-color: #CCCCCC;
}

tr:nth-child(even) {
background-color: #6699FF;
}

Changing between 3 different colors:

tr:nth-child(3n-2) {
background-color: #FF9900;
}


tr:nth-child(3n-1) {
background-color: #006633;
}


tr:nth-child(3n) {
background-color: #CCCC99;
}

As you now know, the nth-child() pseudo-selector retreives all children of a node, regardless of their type. You could do *:nth-child(odd) to do something with every other child in the DOM, beginning with the 1st.

Inside of the selector parameters you put in a multiplier in the format an + b, where “a” is replaced with a multiplier, and “b” is replaced with an offset. So, 3n means every 3rd selected child has an operation done to it. nth-child(3n) would retrieve items 3, 6, 9, and 12. To operate on every third child, but start on the 1st child, use the “b” offset to subtract 2: nth-child(3n -2) will retrieve children 1, 4, 7, etc.

If all you want are alternating rows, you can use the “odd” and “even” keywords, but if you felt excited about CSS, you could also use the nth-child(2n -1) and nth-child(2n) to respectively match the keywords.

Browser Support

Last check: March 17th, 2008

Browser Support? First Version w/Support
Opera Yes 9.5 (in beta)
Konqueror Yes 3.5.4 (not verified)
Safari Yes? r30118 (in alpha, not verified)
Firefox No n/a
Internet Explorer No n/a
Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>