How to display table rows in alternating colors with CSS

Displaying table rows in alternating colors is a common way to help users identify which row they’re focused on. You can use CSS classes to create this effect. You can add to the CSS rules shown in the article How to display spreadsheet data in an attractive and usable way with CSS one additional rule, which is used in the markup:

.datatable tr.altrow {

background-color: #DFE7F2;

color: #000000;

}

You need to modify your markup by adding the altrow class to every second row. This is marked in the next test file with the bold:

 

File test.html

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en-US”>

<head>

<title>How to display table rows in alternating colors with CSS</title>

<meta http-equiv=”content-type” content=”text/html; charset=utf-8″ />

<link rel=”stylesheet” type=”text/css” href=”test.css” />

</head>

<body>

<table class=”datatable” summary=”This table shows Apple Inc. Annual Data for years 2009 through 2012″>

<caption>Yearly Income Statements 2009 – 2012</caption>

<tr>

<th scope=”col”>In Millions of USD (except for per share items)</th>

<th scope=”col”>52 weeks ending 2012-09-29</th>

<th scope=”col”>52 weeks ending 2011-09-24</th>

<th scope=”col”>52 weeks ending 2010-09-25</th>

<th scope=”col”>52 weeks ending 2009-09-26</th>

</tr>

<tr class=”altrow”>

<th scope=”row”>Revenue</th>

<td>156,508.00</td>

<td>108,249.00</td>

<td>65,225.00</td>

<td>42,905.00</td>

</tr>

<tr>

<th scope=”row”>Other Revenue, Total</th>

<td>-</td>

<td>-</td>

<td>-</td>

<td>-</td>

</tr>

<tr class=”altrow”>

<th scope=”row”>Total Revenue</th>

<td>156,508.00       </td>

<td>108,249.00</td>

<td>65,225.00</td>

<td>42,905.00</td>

</tr>

<tr>

<th scope=”row”>Cost of Revenue, Total</th>

<td>87,846.00</td>

<td>64,431.00</td>

<td>39,541.00</td>

<td>25,683.00</td>

</tr>

<tr class=”altrow”>

<th scope=”row”>Gross Profit</th>

<td>68,662.00</td>

<td>43,818.00</td>

<td>25,684.00</td>

<td>17,222.00</td>

</tr>

<tr>

<th scope=”row”>Selling/General/Admin. Expenses, Total</th>

<td>10,040.00</td>

<td>7,599.00</td>

<td>5,517.00</td>

<td>4,149.00</td>

</tr>

<tr class=”altrow”>

<th scope=”row”>Research & Development</th>

<td>3,381.00</td>

<td>2,429.00</td>

<td>1,782.00</td>

<td>1,333.00</td>

</tr>

<tr>

<th scope=”row”>Total Operating Expense</th>

<td>101,267.00</td>

<td>74,459.00</td>

<td>46,840.00</td>

<td>31,165.00</td>

</tr>

</table>

</body>

</html>

The next picture shows the result:

Displaying of table rows in alternating colors with CSS

Displaying of table rows in alternating colors with CSS