Random thoughts & observations

From the mundane to the profound and everything in between here’s what’s rocking our world

CSS zebra striping table rows

Posted: May 9, 2015
Written by: Saints At Play
Category: CSS

One of the great things about modern browser support for web standards is the amount of really cool things that become so much simpler to do than before.

Case in point: alternating the striping of table rows, lists etc - also known as zebra striping.

With CSS this now becomes almost trivial.

If you're using a pre-processor such as Sass (and if you're not you really should think about investing the time to implement this tool into your development process as it will completely change how you write your CSS....for the better) you can accomplish row striping with the following snippet:

$blue: rgb(31, 148, 191);
$turquoise: rgb(135, 184, 207);

tr {
  &:nth-child(even) {
	background-color: $blue;
  }

  &:nth-child(odd) {
    background-color: $turquoise;
  }
}

Thanks to the use of the nth-child pseudo-class we can, in the above example, target table rows in an alternate fashion, specifying the background colour for each alternation of the row.

And that, dear reader, is how easy it is to implement zebra striping with CSS.

Sounds great but what's the catch?

The key phrase at the beginning of this article was modern browser support - this unfortunately means that the following browsers will not, by default, support use of the nth-child pseudo-class:

  • Internet Explorer 6, 7 & 8
  • Opera (prior to version 9.5)
  • Firefox (prior to version 3.5)
  • Chrome (prior to version 1.0)
  • Safari (prior to version 3.1)

You have a number of options available to you in these circumstances:

  • Choose to opt for graceful degradation
  • Assign alternating classes to each separate row that would simulate the above snippet
  • Opt for a jQuery solution that would only stripe the specified DOM elements if the browser falls below the standards support offered by more modern counterparts
  • Implement Selectivizr to add support, via a polyfill, for Internet Explorer 6 to 8 support
  • Simply just ignore it as your site visitors don't use those browsers (analytics packages will help guide your decisions here)

Whichever option you choose is up to you but that's the beauty of web development: there's usually more than one way to solve a problem (or even dismiss it as a problem altogether!)

« Return to Posts

Comments

There are no comments

Posting comments after three months has been disabled.