Alternate row colors with pure CSS3

Posted by Danny Herran on Apr 29, 2011 in Frontend | 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.

  • Pingback: Alternate row colors with PHP | Danny Herran()

  • Naveen

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

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

  • What about select drop down lists?


    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

  • Atila

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

  • Andy Jonathan

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