ColdFusion Tips and Tricks

How to...

Display Alternating Row Colours
Easily in ColdFusion

By: Helen M. Overland
Wednesday, October 12, 2005


When developing ColdFusion applications, it is frequently necessary to display a data report table. It is generally good practice to alternate the background colour of each row, as the end user will usually find the table easier to read.

There are many ways to do this, and they are all perfectly valid. I find, however, that the following method is a neat, quick, and highly flexible method that does not add much complexity to the code.

First, we create a class in our stylesheet. This will enable us to change the row colours at any future time with the absolute minimum amount of redevelopment time.

Add the following class to your stylesheet:
.alt {
	background: #E0E0E0;
}

Now all we have to do is add the class to each alternating row:

<table border="0" align="center">
   <cfoutput query="myquery">
      <tr<cfif currentrow mod 2> class="alt"</cfif>>
         <td>#data1#</td>
         <td>#data2#</td>
         <td>#data3#</td>
      </tr>
   </cfoutput>
</table>

This will produce a table something like the following:

data1 data2 data3
data1 data2 data3
data1 data2 data3


This can be especially compelling when styles are applied effectively:

Header1 Header2 Header3
data1 data2 data3
data1 data2 data3
data1 data2 data3


Why use a ColdFusion/Stylesheet combination?
When an effective stylesheet solution is applied to each table in your application, you have a completely scalable display set that can be easily adjusted for multiple applications. This will help reduce development time by increasing the portability of your code.


Here is the code for the table above:
.report {
	background: #F7EAE2;
	border: 1px solid #A64810;
}
th {
	background: #A03900;
	color: #FFFFFF;
	font-weight: bold;
}
.alt {
	background: #FFFFFF;
}

<table border="0" cellpadding="4" cellspacing="0"
 align="center" class="report">
   <tr>
      <th>Header1</th>
      <th>Header2</th>
      <th>Header3</th>
   </tr>

   <cfoutput query="myquery">
      <tr<cfif currentrow mod 2> class="alt"</cfif>>
         <td>#data1#</td>
         <td>#data2#</td>
         <td>#data3#</td>
      </tr>
   </cfoutput>
</table>