Is it possible, using only CSS, to set different styles on odd and even rows for a dynamically generated table without myself setting correct style on each row when I iterate the collection?
Asked
Active
Viewed 6,030 times
5
-
1See here for a demonstration of the `nth-child` answers: http://stackoverflow.com/questions/5080699/using-css-even-and-odd-pseudo-selectors-with-list-items – thirtydot Feb 23 '11 at 20:10
-
You shouldn't confuse Java and JavaScript (it was retagged for you). See: http://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java – thirtydot Feb 23 '11 at 20:16
-
+1 for jQuery, it exists for a reason, and there really is not any valid reasons not to use it if you are using JavaScript to begin with. – Feb 24 '11 at 03:01
4 Answers
10
I'm not sure this will work cross-browser, i'd prefer jQuery myself, but css-only this should do the trick:
tr:nth-child(even) { ... }
tr:nth-child(odd) { ... }

Peter Smeekens
- 664
- 4
- 9
3
You can use the nth-child
selector http://reference.sitepoint.com/css/pseudoclass-nthchild, though it is not supported by all browsers.
You can also use jquery as described What is the best way to style alternating rows in a table?

Community
- 1
- 1

Jeff Storey
- 56,312
- 72
- 233
- 406
2
You can do this with CSS3.
tr:nth-child(2n+1) /* targets all odd rows */
tr:nth-child(2n) /* targets all even rows */

Intelekshual
- 7,444
- 1
- 21
- 28
1
you can simply use jquery and add class for odd rows like
$("tr:nth-child(odd)").addClass("odd");
and style it using css as
.odd{background-color:#657383}

paul
- 1,124
- 9
- 27
- 45