Advanced CSS Tables – Using CSS3 For Alternate Row Colors

By on  

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.

Track.js Error Reporting

Upcoming Events

Recent Features

  • Designing for Simplicity

    Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...

  • Regular Expressions for the Rest of Us

    Sooner or later you’ll run across a regular expression. With their cryptic syntax, confusing documentation and massive learning curve, most developers settle for copying and pasting them from StackOverflow and hoping they work. But what if you could decode regular expressions and harness their power? In...

Incredible Demos

  • Create a Brilliant Sprited, CSS-Powered Firefox Animation

    Mozilla recently formally announced Firefox OS and its partners at Mobile World Congress and I couldn't be more excited.  Firefox OS is going to change the lives of people in developing countries, hopefully making a name for itself in the US as well.  The...

  • MooTools Equal Heights Plugin:  Equalizer

    Keeping equal heights between elements within the same container can be hugely important for the sake of a pretty page. Unfortunately sometimes keeping columns the same height can't be done with CSS -- you need a little help from your JavaScript friends. Well...now you're...


  1. 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

    • Leonardo

      That didn’t work very well for me, but this did:

      $('tr:odd').css('background-color', '#ccc');
  2. 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!

  3. 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:


  4. Even firefox does not support this CSS3 property.

  5. 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

  6. Matej

    I think Tane meant to write:

    $('tr:odd').css({backgroundColor: '#ccc'});
  7. (And, one year later…)

    Javascript is one method of doing it, sure, but I’d rather just add extra classes and ids everywhere and make my markup really ugly. I actually do surf with javascript turned off in most places, most of the time – I won’t ever see any of these weak workarounds :P

    Safari, Google Chrome and Opera now support this selector. Firefox will support it with the imminent advent of Firefox 3.1, so all the major browsers now support it.
    In 2009 I say just use the CSS. Don’t use javascript, don’t litter your document with extra markup, just use the CSS. Irresponsible advice due to the nature of CSS3 at this time? Maybe.

    But fifty percent (less in USA, more in other countries) of your visitors will be able to use this as soon as Firefox 3.1 shows up. It will degrade nicely, so Virus Explorer users will still be able to see the data…. Just not the alternate row colours (and for those suckers you have conditional comments!)

    PSST Question, David Walsh: are the dates in the comments MM/DD/YY like the Americans or DD/MM/YYYY like everyone else [who doesn’t go largest to smallest descending]?

  8. it would be more better in li element too. I am not sure if

    $('li':odd).css({backgroundColor: '#ccc'});
    $('li':even).css({backgroundColor: '#ff0000'});

    will work


    Thanks a lot…. this is a great code you have… I am currently using CSS 3 and dont have all the codes to help me achieve what I have in mind… But thanks to you I now have the solution..

  10. @ROBPANE:
    Do you have solution for li element as tr does .

  11. Carlos

    thanks for posting this !! still useful info in 2010

  12. smriti

    Thanks for the solution. Was trying to achieve alternating row colors in CSS for quite sometime. I have one issue. When i apply tr:nth-child(odd){background-color: #AFC7C} the background color is applied to more area around the table than just simply the row. However tr:nth-child(even)
    { background-color: #AFC7C7;} works as expected.

  13. Interesting. CSS starts off at 1 (odd) and javascript is 0 based. So it starts off even. Still relevant in 2010. I’m not worried about users turning javascript off.

  14. I have found this CSS selector very useful. Its true that not all browsers support the latest CSS3 statement so this would fall into the bracket of Progressive Enhancement. Combining the call to style for odd rows within a , or using JQuery will support older browsers that do not support CSS3 which is a bonus.

    Also there is a plugin to support CSS3 called CSS3pie http://css3pie.com/, I am using it at the moment on a couple of projects. One problem I have found is applying rounded corners “border-radius” to submit form buttons. This does not work in IE6.

  15. Steppo

    Stop caring about IE6, please…! You only support people not switch to to modern browsers.

  16. Sarah

    Here’s a link for down the line, when all major browsers will support CSS3:


  17. Mike

    @Sneaky…….. MM/DD/YY makes more sense.

  18. How about with the use of regular JavaScript (without any framework) and CSS1 which can be supported by all the users, including IE6 :) – http://acmeous.blogspot.com/2011/10/how-to-color-alternate-rows-in-table.html

  19. Corey

    @Mike Exactly how does “MM/DD/YY” make sense? Because it aligns to the (purely US) grammar convention of placing the month first when speaking the date?

    For the rest of us the concept of putting day, month, year in a mixed sequence – whether verbally or in text form – is at best silly. Logically days are segments of months, months segments of years, so it “makes more sense” to place them in container sequence – internal to external as “DD/MM/YYYY” or external to internal as “YYYY/MM/DD” – rather than picking an arbitrary order based on linguistic peculiarities. As a bonus “YYYY/MM/DD[ hh:mm:ss]” makes for much simpler text sorting.

    I’m curious though… do you write your address as “City, Street, State”? Do you write your name as “Initials, First Name, Surname”?

    I imagine not :)

    (I’m going to stop now before I launch into the “Metric vs Imperial” or “Celsius vs Fahrenheit” debate)

  20. I really like the idea of using jQuery to change my alternating row colors. David, not trying to dawg you out, however the notion of “what if they turn off javascript” is old news. Honestly, I do not know of anyone who turns off Javascript, and most modern cell phones have javascript installed on their browsers. jQuery is the also becoming more of a standard and will work in non CSS3 browsers, like the dreaded IE8, which unfortunately, many users are still surfing with. Keep up the good articles, and the CSS3 pseudo class method is a great way to do it as well.

    • This was posted August 10, 2007. I know the JavaScript concern is mostly over.

  21. Ashay

    dont cry for IE thats solution work in IE also
    background-color:expression( (this.rowIndex %2 == 0) ? ‘#FFF’ : ‘#OOO’ );

  22. Almost 5 years ago – but still valid as a quick reference, first hit in google and already pasted on my css, Firefox, Chrome and IE9 supports it so great! :)

  23. Nate

    Thanks man! great tip

  24. Adam

    Love this, 2007 and still relevant..

  25. rebotak

    hahaha, now 2013 and still relevant!

  26. Hey David Walsh. I have to say that this worked like a charm! I am more of a designer than a coder. Thank you.

  27. Suresh

    I want to know the code, When the 3rd, 6th, 9th row of the table wants to be shaded or colored.

    • we
      tr:nth-of-type(3n) {background-color: grey;}

      subsequently this also selects all other further multiples of 3. From 9 on, the 12th, 15th, 18th row and so on.
      To target just those specific rows in less code than

      tr:nth-of-type(3),tr:nth-of-type(6),tr:nth-of-type(9) {background-color: blue;}

      though seemingly requires either using another language (or template) because actually, as according to tutsplus.com, “nth-child” is a fairly recent innovation. thus is the joy of css3. (“3,6,9″, even “3&6&9″ would be so ideal though! It probably conflicts something a bit higher up in level that a fellow beginner like me cannot fathom..)


  28. Suresh

    Hello All,

    Please help us to find out the code for the specific cells in the rows to be colored with the Advanced CSS..

  29. Hi Suresh,

    Try reading the “Even and odd Rules” of this page:

    Good luck!

  30. Andy

    Hahaha ! 2014 and still relevant ! Thanks guys !

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • OâReilly Velocity Conference â Amsterdam

    My favorite front-end conference has always been O'Reilly's Velocity Conference because the conference series has focused on one of the most undervalued parts of client side coding:  speed.  So often we're so excited that our JavaScript works that we forget that speed, efficiency, and performance are just as important. The next Velocity...

  • CanIUse Command Line

    Every front-end developer should be well acquainted with CanIUse, the website that lets you view browser support for browser features.  When people criticize my blog posts for not detailing browser support for features within the post, I tell them to check CanIUse:  always up to date, unlike...

  • Generating Alternative Stylesheets for Browsers Without @media

    If your CSS code is built with a mobile-first approach, it probably contains all the rules that make up the "desktop" view inside @media statements. That's great, but browsers that don't support media queries (IE 8 and below) will simply ignore them, ending up getting the...

  • Serve a Directory with PHP

    Many developers have a giggle at PHP, even looking down at the language, but let's be honest:  most of our blogs are powered by it (WordPress) and it's a great language to dabble around with.  I cut my teeth on PHP, though I prefer to avoid PHP these days. But...

  • Tips you can Use to Build an Excellent eCommerce Experience

    There are many reasons to build a good eCommerce experience if you are planning to build an eCommerce website. Visitors can place items in their cart and leave your site without making a purchase. In fact, three out of every four of them will do so....