Alt-Web Design & Publishing
CSS3 Zebra Table with :Nth-Child Selectors
Description:
Table rows with alternating background colors or stripes are commonly known as Zebra Tables. In our previous demo, we applied a class name (.odd) to every other table row. Now with a bit of CSS3 and the nth-child selector (actually a pseudo-selector), we can automatically apply styles to alternating elements without additional HTML or JavaScripts.
Tested and works in IE9+, Firefox3.5+, Chrome, Safari & Opera.
NOTE: Nth-child pseudo-selectors are not fully supported in legacy browsers like IE6 - 8. If you must support older browsers, please use the method described in Zebra Table styled with CSS2.
Example:
| Table Header 1 Subtitle |
Table Header 2 Subtitle |
Table Header 3 Subtitle |
|---|---|---|
| even | some text here | some text here |
| odd | Some text here | Some text here |
| even | Some text here | Some text here |
| odd | Some text here | Some text here |
Method:
CSS3 Code
table {
width: 90%;
border: 2px groove silver;
font: 12px Geneva, Arial, Helvetica, sans-serif;
margin: 0 auto; /**centers table on screen**/
}
caption {
font-size: 2em;
text-align:left;
color: #336699;
font-style:italic;
line-height: 1.8;
font-weight: bold;
}
th {
font:16px bold Arial, Helvetica, sans-serif;
color: maroon;
text-align:center;
background-color: #FFFF99;
}
th,td,tr {border: 1px solid silver; vertical-align:middle; height: 45px; }
em {font-size: 14px bold; font-style:italic; color:#000;}
/**Zebra Stripes**/
tr:nth-child(even)/**every even row**/
{background-color: #F1F1F1;}
tr:nth-child(odd) /**every odd row**/
{background-color: #ECE7CA;}
XHTML Code
<table cellspacing="0" cellpadding="5">
<caption>Zebra Table styled with CSS3 nth-child selectors </caption>
<tr>
<th>Table Header 1<br />
<em>Subtitle</em></th>
<th>Table Header 2 <br />
<em>Subtitle</em></th>
<th>Table Header 3<br />
<em>Subtitle</em></th>
</tr>
<tr>
<td>even</td>
<td>some text here</td>
<td>some text here</td>
</tr>
<tr>
<td>odd</td>
<td>Some text here</td>
<td>Some text here</td>
</tr>
<tr>
<td>even</td>
<td>Some text here</td>
<td>Some text here</td>
</tr>
<tr>
<td>odd</td>
<td>Some text here</td>
<td>Some text here</td>
</tr>
</table>
