...

View Full Version : Alternating <TR> styles in tables



donmerlin
12-03-2005, 10:57 AM
When I saw the first-child pseudo class, I thought for sure there would be an odd-child and even-child class (to allow me to color band my HTML tables). Alas, no such beast exists as far as I can tell. I'm looking for a CSS shortcut or trick for taking a generic table and making every other row a different background color. In the past, I just used HTML to change the colors of every other row manually, but this is a major headache when you continually add and delete rows (because then you have to re-adjust all the other rows). I'm currently using the following CSS hack, but it has two problems, which is why I'm looking for a new solution. The first problem is that it's a finite definition (aka, once the table goes beyond the definition, the colors are not applied). The 2nd problem is that it's a nasty looking hack. I'd be interested in knowing if anyone else has done something like this in a more elegant way.

Thanks!

table tr:first-child+tr, tr:first-child+tr+tr+tr, tr:first-child+tr+tr+tr+tr+tr,
tr:first-child+tr+tr+tr+tr+tr+tr+tr, tr:first-child+tr+tr+tr+tr+tr+tr+tr+tr+tr,
tr:first-child+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr,
tr:first-child+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr,
tr:first-child+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr,
tr:first-child+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr,
tr:first-child+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr,
tr:first-child+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr,
tr:first-child+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr,
tr:first-child+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr,
tr:first-child+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr,
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tr+tr,
tr:first-child+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+t r+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr+tr
{
color: blue;
background-color: rgb(222,222,222);
}

rmedek
12-03-2005, 12:42 PM
whoa, all those pluses are making me dizzy :D

It'd also never work in IE, as IE doesn't support the first-child or the sibling selectors. I ran into a problem on a site I was designing as well, where the table was generated by a CMS so I'd never know how many rows there were.

A List Apart to the rescue: http://www.alistapart.com/articles/zebratables/

The Javascript solution described is pretty much right on the money, and it degrades gracefully.

Hope this helps...

macmonkey
12-04-2005, 08:27 PM
This can also easily be achieved if you are using php to output data from a database.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum