CSS can be used to create a table with alternating row colours. Historically this required editing of individual item rows.
Using CSS to define the odd and even table row colours works particularly well for a CMS website. Content can be created and edited without maintaining the row colours. Adding or deleting a row in a long table can make for tedious changes to the row colour settings.
In CSS3 a definition is added for the element which is changing, in this case tr and a reference to its child :nth-child.
tr:nth-child(even) { background-color:#dff; }
tr:nth-child(odd) { background-color:#dee; }
As shown here the rows are referenced using odd and even.
| Fruit | Qty |
|---|---|
| apples | 5 |
| bananas | 37 |
| oranges | 6 |
| plums | 35 |
| quinces | 4 |
An alternative is to use a reference to n, the odd and even equivelent is 2n and 2n+1:
.mArticles tr:nth-child(2n) td {
background-color:#dff;
}
.mArticles tr:nth-child(2n+1) td {
background-color:#dee;
}
For this website the odd and even row settings have been defined for use in the table class. This is used in a number of articles, for example the list of country codes:
www.vntweb.co.uk/country-codes/
The use of 2n and 2n+1 can be extended to have a row colour repeat of 3, 4 or more rows, for example:
.mArticles tr:nth-child(3n) td {
background-color:#dff;
}
.mArticles tr:nth-child(3n+1) td {
background-color:#dee;
}
.mArticles tr:nth-child(3n+2) td {
background-color:#ddd;
}
A series of repeating divs can also be defined in a similar way, simply be ascertaining the repeating element.
The use of the nth-child pseudo class to determine table rows will suffer from browser compatibility, with limited support from Internet Explorer and more wide spread support from the active versions of the other main browsers.


