← Back to the front-page.

Zebra striping a table with CSS

I'm working on the new user interface for the JavaScript Profiler in Firefox and yesterday I was implementing a top-down representation of our profiler data. Top-down view, for those who don't know, is basically a table that shows an overall picture of the calling structure, starting at the top of the call stack. It looks something like this:


As with any tabular data it's easier on your eyes when the background is striped. Since we're not in the IE6 world anymore, the most obvious solution for me was to use nth-child(even) CSS selector.

This worked well until I had to hide some of the rows. What I learned yesterday is that nth-child(even) doesn't respect any previous selectors. So all my efforts to make something like :not([hidden]):nth-child(even) work failed miserably. It's just not possible.

What everyone seems to be doing is using a repeating linear background image to add striped backgrounds to their tables. Seriously, this is what people are using:

  repeating-linear-gradient(white, white 25px, hotpink 25px, hotpink 50px);

If this is not an ugly hack, I don't know what is.


Christian Heilmann came up with another approach where you remove rows from the table, cache them and then re-insert when needed. His example is on JSBin.

I'm Anton Kovalyov. I write software and work at Medium. I also created the JSHint project. Other projects: oddweb, hirojs, ministruct.

You can find me on GitHub or Twitter. But the best way to communicate with me is by sending an old-fashioned electronic mail.