Welcome to the David Walsh Blog! This website was created to reach every audience possible. Please contact me at david@davidwalsh.name to let me know if I can do anything to further improve your experience on this website.

The Article


Bookmark and Share

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.

8 Quality Comments

8-11-07
12:32 pm

Tane Piper says:

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

davidwalsh83
8-11-07
12:50 pm

davidwalsh83 says:

I’m aware that jQuery allows for this type of programming, but what if a user was to turn off their javascript or the user wasn’t web-savvy and didn’t know how to get their javascript back on? Don’t you think this should be a CSS capability?

Thank you for your insight!

8-11-07
6:14 pm

FlySwat says:

A good example of how to do this with javascript until browsers support CSS3 (years? :D ) without using jQuery can be found on my blog here:

http://www.geeksnotnerds.com/flyswat/building-better-zebra-table

1-17-08
11:03 am

plasebo says:

Even firefox does not support this CSS3 property.

4-08-08
6:45 am

Pariah says:

Safari supports this CSS3 class now. Just realized as I had it already implemented on one of my sites ages ago and after updating safari and stumbling upon it again i noticed it was working a treat! Safari all the way! Woo! LOLOLOL

9-11-08
2:26 pm

Matej says:

I think Tane meant to write:

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

Be Heard!

Your email is never published nor shared. Required fields are marked *.

Name*:
Email*:
Website:  


 

 

 

comments twitter