We used to do this with either javascript (by adding and removing class names to our table rows), or with html (by adding class names to alternating rows), but CSS3 now let's us do this really easily. Here's my example:
The Code
It's pretty straight forward actually; our table here is totally typical with no added classes or markup than you would normally include. The zebra striping here comes from utilizing the following:
tr:nth-of-type(even) td {
background: #eee;
}
What this does is for every even table row, add a light gray background to all of it's table data cells. You could easily alternate by odd rows as well:
tr:nth-of-type(odd) td {
background: #eee;
}
There's lots of other things you can do too, like stripe every 3rd row:
tr:nth-of-type(3n) td {
background: #eee;
}
Or stripe every 3rd row, but include the first row:
tr:nth-of-type(3n+1) td {
background: #eee;
}
Here, I opted for the standard even row alternating zebra striping, but also added a hover just because I like that effect:
tr:hover td {
background: #08d;
}
Anyhow, that's all there is to it.Full Demo with Code
Browser Support
As with most juicy CSS3 stuff, IE8 and older doesn't handle this feature (specifically the "nth" type selectors). If you really must support zebra striping for these users, you'll have to fall back to the old school way of doing so, but given the additional work involved in that for such little benefit, it seems a better idea to let those users experience your otherwise perfect table.
No comments:
Post a Comment