When displaying large groups of data, especially wide sets in which the user’s eye has to travel from one side of the screen to the other, it’s always a good idea to having a slight variation between alternating rows, for ease of reading. Like so:
- odd
- even
- odd
- even
- odd
- even
- odd
<rant>Astute observers will note I’ve used an unordered list for my sample. This is not to suggest one should use them for multi-cell data sets — in that situation, a table really is what’s called for. Yes, a table. I know, I know. We all remember the terrible “tables of tables” design phase a couple of years ago and no one wants to go back there. But c’mon people. Data sets are what tables are meant for.</rant>
It’s simple enough to create the styles for alternative rows. Set one style as the default, then define the other in a class and apply to alternating rows.
But who has the time to paste a class into alternating rows? And what if the data set is dynamic, like search results that can be sorted by a couple of different elements? Isn’t there an easier, lazier way of doing this?
For old browsers, no there isn’t. Nor is there for (big surprise) IE, up to (and including) version 8.
But for everyone else living in the 21st century, yes there is: Nth Child.
While one can set all sorts of crazy rules with it (here’s a good explanation, if you’re curious) what we’re really looking for is a solution to the problem above. Nth Child does it with two options: even and odd.
Here’s the CSS and HTML for my example above:
<style>
ul#sample {
list-style: none;
}
#sample li {
border-top: 1px solid #fff;
padding: 5px;
/* here we set the default background color */
background: #eee;
}
/* and here we set the alternating color */
#sample li:nth-child(even) {
background: #ddd;
}
</style>
<ul id="sample">
<li>odd</li>
<li>even</li>
<li>odd</li>
<li>even</li>
<li>odd</li>
<li>even</li>
<li>odd</li>
</ul>
Using tables? As long as you reference the correct elements nth child does tables too.
It could not be simpler. Unless, of course, you’re Microsoft.