Feb 22, 2011

Advanced CSS Tables – Using CSS3 For Alternate Row Colors

CSS finally addresses an issue that I've been peeved wasn't fixed earlier. The DIV movement of getting away from table-based design taught us that tables should be used only when you're presenting a table of data on your website, yet no CSS selector/rule was created to allow us to shade alternate rows a different color. Isn't that a basic design / usability need?

CSS3 will include a ":nth-child(argument)" pseudo-class which will allow us to control the display of alternate rows without using extra CSS classes, JavaScript, or server-side code to manage the alternating CSS class placement. The kicker? No one seems to fully support CSS3 yet. Here's how you'll be able to achieve this in the future.

tr:nth-child(odd)   { background-color:#eee; }
tr:nth-child(even)    { background-color:#fff; }

Until all modern browsers support this, we'll need to use CSS classes and/or JavaScript. A problem fixed late is better than a problem not fixed at all.


This can already be done cross-browser using the JavaScript library jQuery very easily.

$(‘tr’:odd).css({backgroundColor: ‘#ccc’});

That adds a different background color to any table odd row.
Check it out at http://jquery.com

No comments: