Zebra striped tables in pure CSS for IE7 and IE8

Ian Routledge
ediblecode
Published in
2 min readJul 24, 2012

Zebra striping, as it is called, is a common technique used to distinguish rows in an HTML table. The technique basically makes tables easier to read.

It *should* be something that’s easy and straightforward to build, however, as always with CSS and HTML there are a number of different ways to achieve the same goal which have differing outcomes in different browsers. Below are the most common techniques and then I’ve outlined a technique that works for IE7 and IE8 too. Here are the normal techniques:

  1. Add a class of ‘odd’ to odd numbered tables rows on the server side when the table is generated/rendered. Makes the markup slightly less clean and involves extra work on the server.
  2. Add an ‘odd’ class to odd numbered rows with jQuery, something like: $(“tr:odd”).addClass(“odd”);. Requires javascript.
  3. Use the CSS3 nth-child pesudo-selectors to style odd and even rows separately. Doesn’t work in old browsers.

As you can see, none of these methods are perfect, so here’s another non-perfect technique. It makes use of both the CSS2 adjacent sibling combinator and the CSS3 general sibling selector (the ~). Fortunately, IE7 supports both selectors, even support is buggy. This solution does have 2 problems though, which are:

  1. It is really fugly.
  2. It only works for tables up to a finite length (and requires you to extend the CSS for as long as you need it).

Basically it looks like this:

[sourcecode language=”css”]
tr+tr
, tr+tr+tr+tr
, tr+tr+tr+tr+tr+tr
, tr+tr+tr+tr+tr+tr+tr+tr { background: Red; }
tr+tr~tr
, tr+tr+tr+tr~tr
, tr+tr+tr+tr+tr+tr~tr
, tr+tr+tr+tr+tr+tr+tr+tr~tr { background: White; }
[/sourcecode]

Which makes a lovely red and white striped table up to 9 rows high that works in IE7 and IE8 as well as modern browsers. You can easily extend the CSS to work with more rows, which does admittedly make your CSS look even uglier.

Also, you can easily adapt it to work for other elements, not just rows. For example an unordered list where you wanted to float odd items left and even items right.

--

--

Ian Routledge
ediblecode

Lead Developer at NICE. Taking over the world one line of code at a time.