Alternate row colors with pure CSS, yes, CSS3

Posted by on Apr 29, 2011 in CSS | 6 Comments

Pure CCS3 Alternate Row Colors CSS3 is here. All the modern browsers support it, even the infamous Internet Explorer in its 9th version. In this small article we will learn how to alternate row colors in a table, or any other HTML element with pure CSS3. The best part is that you will be able to do it in just 2 lines. No more PHP hacks or JavaScript chunky chunks.

I know I posted a few months ago a way to alternate row colors with PHP (which is kinda nice), but lets be honest, mixing CSS + PHP is not as beautiful as pure CSS. If you might want to check that article if CSS3 is not an option for you.

Enough jibber jabber, lets take a look at the code:

tr:nth-child(odd) { background:#000; }
tr:nth-child(even) { background:#333; }

That would do it for a table. Lets see how to do it on a list element:

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

Magic isn’t it? I will make sure to post any other cool CSS3 solutions whenever I find them around.

Have fun!

Cool stuff: The new Google Chrome logo made only with CSS3.

6 Comments

  1. Alternate row colors with PHP | Danny Herran
    April 29, 2011

    [...] you might be interested in how to alternate row colors with pure CSS. Share and [...]

    Reply
  2. Naveen
    July 30, 2011

    Is it works well in IE browsers also? Can you give me example for IE.

    Reply
    • Danny Herran
      July 30, 2011

      It works on IE9. IE8 and IE7 would need a manual method to achieve the same effect.

  3. dan plesse
    May 27, 2012

    What about select drop down lists?

    this:

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

    or this:

    select:nth-child(odd) { background:#000; }
    select:nth-child(even) { background:#333; }

    or that

    Reply
  4. Atila
    August 24, 2012

    Great!! Thanks for sharing the knowledge. Worked beautifully! o/

    Reply
  5. Andy Jonathan
    November 20, 2012

    Could I use something similar but for text contained in a tag ?

    Reply

Leave a Reply