How to create zebra stripes on html table without using javascript and even/odd classes generation?

CssHtml Table

Css Problem Overview


I want to zebra-stripe a html table without using any js stuff or writing server-side code to generate even/odd classes for table rows. Is it ever possible to do using raw css?

Css Solutions


Solution 1 - Css

It is possible, with CSS3 selectors:

tr:nth-child(even) {
  background-color: red;
}


tr:nth-child(odd) {
  background-color: white;
}

According to caniuse.com, every browser supports it now.

Solution 2 - Css

If all you're changing is the background colour, then the following would work, where test.gif is a 40px high image with the top 20px one colour, and the bottom 20 pixels the other colour. If you need to change any other css properties you're pretty much stuck.

table {  background: url(test.gif) top; }
table tr { height: 20px; }

Solution 3 - Css

http://www.w3.org/Style/Examples/007/evenodd CSS 3 nth-child. Since browser support is limited you can reproduce the behavior with Sizzle (included in, jquery for example)

Solution 4 - Css

(In CSS <= 2) Nope. Unfortunately there aren't any selectors (in CSS <= 2) that operate based on the position (in terms of the number it is within it's parent's children) which I believe you would need to do this with just CSS.

Note to self: read up on CSS3, already!

Solution 5 - Css

In http://www.w3.org/TR/css3-selectors/#structural-pseudos you can find explanation and examples on using nth-child:

tr:nth-child(2n+1) /* represents every odd row of an HTML table */ {
  background-color: green;
}
tr:nth-child(odd)  /* same */ {
  background-color: green;
}
tr:nth-child(2n+0) /* represents every even row of an HTML table */ {
  background-color: pink;
}
tr:nth-child(even) /* same */ {
  background-color: pink;
}

Good luck with browser compatibility - you'll need it.
There are hacks to make it work in IE (using JS) - I'll leave that sifting to you.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVladimirView Question on Stackoverflow
Solution 1 - CssK. NorbertView Answer on Stackoverflow
Solution 2 - CssScottEView Answer on Stackoverflow
Solution 3 - CssFrancisco AquinoView Answer on Stackoverflow
Solution 4 - CssicioView Answer on Stackoverflow
Solution 5 - CssANevesView Answer on Stackoverflow