views:

444

answers:

7

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?

A: 

You can accomplish this with jQuery. There is a decent article explaining how to do it here.

jaltiere
Yes, but the question is how to do it without javascripting.
Vladimir
He did specifically mention "no" javascript.
Josh
my fault, I saw the part that said no server side scripting, completely missed the no js part.
jaltiere
+9  A: 

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.

WishCow
+1, would +2 for "modern" if I could.
ANeves
A: 

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)

F.Aquino
A: 

(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!

icio
A: 

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.

ANeves
A: 

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; }
ScottE