2

is it possible to set the style of alternating rows in a html table with style selectors that only take account of the hierarchy of elements and do not use style names?

i need to style html output produced by a server component and the output does not set styles for alternating rows. i could write a javascript (or just as well change the component) but i am curious about whether it is possible to do in pure css.

thanks konstantin

akonsu
  • 28,824
  • 33
  • 119
  • 194

1 Answers1

10

In CSS 3:

tr:nth-child(odd)    { background-color:#eee; }
tr:nth-child(even)    { background-color:#fff; }

And in CSS 2, you have to use some class on e.g. even rows like:

.even { background-color: #00000; }

and you have to apply them when generating the rows server-side (or in hand ;-) ) or with e.g. jQuery like:

$(document).ready(function () {
    $("tr.nth-child(even)").addClass("even");
    //Or
    $("tr:even").addClass("even");
});
Lasse Espeholt
  • 17,622
  • 5
  • 63
  • 99
  • Now days update: as posted [here](http://stackoverflow.com/a/11222732/1207195) you can use [selectivizr](http://selectivizr.com/) to emulate CSS3 selectors on IE6-8 (your CSSs will work with that versions and browsers with good support won't be polluted by tricks for IE) – Adriano Repetti Jun 27 '12 at 09:39