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?
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?
Share Improve this question edited Sep 18, 2018 at 6:40 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Feb 23, 2011 at 20:06 per_janssonper_jansson 2,1895 gold badges29 silver badges50 bronze badges 3-
1
See here for a demonstration of the
nth-child
answers: stackoverflow./questions/5080699/… – thirtydot Commented Feb 23, 2011 at 20:10 - You shouldn't confuse Java and JavaScript (it was retagged for you). See: stackoverflow./questions/245062/… – thirtydot Commented Feb 23, 2011 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. – user177800 Commented Feb 24, 2011 at 3:01
4 Answers
Reset to default 10I'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) { ... }
You can use the nth-child
selector http://reference.sitepoint./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?
You can do this with CSS3.
tr:nth-child(2n+1) /* targets all odd rows */
tr:nth-child(2n) /* targets all even rows */
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}