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

5

59

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?

Albertson answered 4/5, 2010 at 13:8 Comment(0)
C
127

It is possible, 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.

Cida answered 4/5, 2010 at 13:14 Comment(2)
by modern you mean everything but IE7 and 8Meghannmegiddo
You'd probably want to scope it as tbody tr:nth-child(even) so it only applies to rows in the table body and not the <thead> or <tfoot> which are usually styled differently.Insincere
C
3

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; }
Celina answered 4/5, 2010 at 13:25 Comment(3)
That is a singularly inflexible approach.Costume
@Mike Adler - absolutely, but for browsers that don't support :nth-child, and without js/server side changes there's not much you can do.Celina
Clever. Though, this will annoy users who need to read larger text sizes than will fit in the 20px cell height.Fight
C
1

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)

Caracalla answered 4/5, 2010 at 13:15 Comment(0)
G
0

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

Gallegos answered 4/5, 2010 at 13:15 Comment(0)
P
0

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.

Pedicular answered 4/5, 2010 at 13:16 Comment(1)
You don't even need the +0 on 2n+0Snowden

© 2022 - 2024 — McMap. All rights reserved.