How to create zebra stripes on an html table without using javascript generation and even / odd classes?

I want a zebra-stripe html table without using any js files or writing server side code to create even / odd classes for table rows. Can raw css be used?

+56
css html-table
May 04 '10 at 13:08
source share
5 answers

Perhaps with CSS3 selectors:

tr:nth-child(even) { background-color: red; } tr:nth-child(odd) { background-color: white; } 

According to caniuse.com , every browser supports it now.

+120
May 4 '10 at 1:14 p.m.
source share
— -

If all you change is the background color, then the following will work: test.gif is an image 40 pixels high with the top 20px in one color and the bottom 20 pixels in a different color. If you need to change any other css properties, you are very stuck.

 table { background: url(test.gif) top; } table tr { height: 20px; } 
+3
May 04 '10 at 13:25
source share

http://www.w3.org/Style/Examples/007/evenodd CSS 3 nth-child. Since browser support is limited, you can reproduce the behavior using Sizzle (including, for example, jquery)

+1
May 04 '10 at 13:15
source share

(In CSS <= 2) None. Unfortunately, there are no selectors (in CSS <= 2) that work depending on the position (in terms of the number that it is inside of its parent children), which, I believe, you will need to do this only with CSS.

Note to yourself: read on CSS3 already!

0
May 04 '10 at 13:15
source share

At http://www.w3.org/TR/css3-selectors/#structural-pseudos you can find an explanation and examples of 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 need it.
There are hacks to make it work in IE (using JS). I will leave this sifting.

0
May 04 '10 at 13:16
source share



All Articles