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?
views:
444answers:
7How to create zebra stripes on html table without using javascript and even/odd classes generation?
You can accomplish this with jQuery. There is a decent article explaining how to do it here.
It is possible, but only with CSS3 selectors:
tr:nth-child(even) {
background-color: red;
}
tr:nth-child(odd) {
background-color: white;
}
Modern browsers already support it.
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)
(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!
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.
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; }
See the php way at bottom of this article
http://cookbooks.adobe.com/post_Alternate_colors_for_table_rows-16650.html
another way
http://lorenzod8n.wordpress.com/2007/06/02/alternating-row-color-in-htmlcss-with-php/