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.

Recent Features

  • By
    5 HTML5 APIs You Didn’t Know Existed

    When you say or read "HTML5", you half expect exotic dancers and unicorns to walk into the room to the tune of "I'm Sexy and I Know It."  Can you blame us though?  We watched the fundamental APIs stagnate for so long that a basic feature...

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

Incredible Demos

  • By
    Sexy Opacity Animation with MooTools or jQuery

    A big part of the sexiness that is Apple software is Apple's use of opacity. Like seemingly every other Apple user interface technique, it needs to be ported to the web (</fanboy>). I've put together an example of a sexy opacity animation technique...

  • By
    Image Reflection with jQuery and MooTools

    One subtle detail that can make a big difference on any web design is the use of image reflections. Using them too often can become obnoxious but using reflections on large, "masthead" images is a classy enhancement. Unfortunately creating image reflections within your...

Discussion

  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:

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

  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

  9. ROBPANE

    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 .

    • Aamir
      #mytag li div ul li:nth-child(even) {
          background-color: #cdcdcd;
      }
  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:

    http://davidwalsh.name/css-tables-css3-alternate-row-colors

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

      -Lin

  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:
    http://www.w3.org/Style/Examples/007/evenodd.en.html

    Good luck!

  30. Andy

    Hahaha ! 2014 and still relevant ! Thanks guys !

  31. Feri

    hahha! 2017 and still working happily!

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