XML technologies / CSS / CSS Cookbook / Tables / Alternating background colors for table columns

(Excerpt from “CSS Kochbuch” by Christopher Schmitt)

Problem

Give the table in the next figure alternating background colors, as shown in the figure after it.

Table without cell background colors

Figure: A table without cell background colors.

Solution

Create a separate class for odd-numbered table rows ( odd):

tr {
 background-color: #eee;
}
tr.odd {
 background-color: #ccc;
}

Then give every other row in the table the appropriate attribute class with the value odd:

<tr>
  ...
</tr>
<tr class="odd">
  ...
</tr>
<tr>
  ...
</tr>
<tr class="odd">
  ...
</tr>
<!-- und so weiter... -->

Table rows with alternating background colors

Figure: Table rows with alternating background colors.

Discussion

Manually giving every other element tr an attribute class can be laborious, especially in long tables. However, this technique works in all CSS-capable browsers.

A second solution needs no additional markup in the HTML table. It uses the pseudo-class defined in the CSS 3 specification :nth-child:

tr {
 background-color: #eee;
}
tr:nth-child(odd) {
 background-color: #ccc;
}

However, support for CSS 3, including :nth-child, is very limited in Internet Explorer 6 for Windows and earlier versions. Until all browsers are supported, this method is therefore probably less suitable.

JavaScript

Other solutions go beyond CSS alone. For example, one way to give table rows alternating background colors uses JavaScript code that interacts with the Document Object Model (DOM) and automatically applies the styles to every other table row. For an example of this approach, see A List Apart: Zebra Tables. Its drawback is that it works only if the user has enabled JavaScript in their browser.

Server-side solutions

Another solution is to use a server-side programming language such as PHP or ColdFusion. A simple script can automate table generation. (This technique is also useful when a database backend generates and manages the table data.)

See also

The CSS 3 specification for the pseudo-class based selector :nth-child.

  

 

 

 

back to top