Page 1 of 1

Styling Tables With CSS 3.0 Pseudo-Classes! Rate Topic: -----

#1 RetardedGenius   User is offline

  • >>──(Knee)──►
  • member icon

Reputation: 127
  • View blog
  • Posts: 555
  • Joined: 30-October 10

Posted 27 July 2011 - 10:06 AM

How to Create "Zebra" Tables with CSS 3.0 Pseduo-Classes!

Hello everyone, I was initially going to submit this as just a code snippet but I realised that it would be better if complemented by an explanation, so I made it into a short tutorial.

What's a "Zebra" table?
"Zebra" tables are tables where every other row has a different background colour, this helps a reader distinguish between adjacent rows and also makes it more stylish (in my opinion). A classic example of Zebra tables would be the iTunes interface.

Can't I do this all ready?
Well yes, but most implementations are less than ideal, typically relying on Javascript to add classes to every other table row which are then styled with CSS, or even worse coding it manually in HTML!

Below I have included an example of what I am talking about, here is its output. I've used some basic CSS styling to make it "pretty", the content of the table was actually generated with a small PHP script that I wrote but that's something else entirely, all that matters is that the table's content is tabular!


CSS 3.0 Comes to the Rescue!
As you can see, the above is clearly less than ideal, I have given the every <td> element inside every other table-row the even class which has a unique styling, but don't despair CSS 3.0 introduces the perfect pseudo-class for this.

By using the :nth-child pseudo-class I can style every other row in my table without having to change the HTML, making it much neater and more convenient to work with. If I use the style:

tr:nth-child(even) td {
    background-color: #F5E7F5;

I can now achieve the same effect, I've included the code for the full example below, you can view the output here.


There's More
That's only touching the tip of the ice-berg of what can be done with this powerful new tool, it can be applied to many other HTML elements, e.g. unordered and ordered lists. You can specify numerical parameters for it as well, let's say I wanted to style every 2nd row, starting from the 5th, I could do that in a second like this:

tr:nth-child(2n+5) td {
    background-color: #F5E7F5;

and that would instantly, dramatically modify the appearance of my table, regardless of how much data it contains. :smartass:

This post has been edited by RetardedGenius: 15 October 2011 - 04:31 PM

Is This A Good Question/Topic? 1
  • +

Page 1 of 1