May 29, 2012

Using Standard Salesforce CSS and JavaScript to Style HTML Tables

I recently needed to create a visualforce table that displays a list of records, but also had a permanent editable first row through-which a user can quickly add new records. I used an HTML table shell and a visualforce REPEAT to create the rows. However, since I did not use one of the the normal visualforce table elements, I had to use the standard Salesforce CSS and javascript elements in order to mimic the Salesforce table look and feel. The standard CSS and javascript libraries are included on every visualforce page (unless specified otherwise), so all you need to do is add some classes and events to your table tags.

Here is a list of useful table-related styles you can use. Salesforce styles are case sensitive.
  • .list - add to <table> along with border="0" cellspacing="0" cellpadding="0".
  • .headerRow - add to <tr> to display column headings
  • .dataRow - add to <tr> to display record rows.
  • .dataRow last - add to <tr> to display record rows without line separation between rows. Usage: class="dataRow last".
  • .dataCell - add to <td> to display cells (this is normally not needed).
  • .CurrencyElement - helpful in <td> and <th> when displaying currency in cells.
  • .PhoneNumberElement - helpful in <td> and <th> when displaying phone numbers in cells.
  • .DateElement - helpful in <td> and <th> when displaying date/datetimes in cells.
  • .btn - Not related to tables, but useful to format anchors as buttons.

If you also want the standard onMouseOver effect in your table (row changes color on when you hover over it), you'll need to add the following to your table row:
A quick note before the sample... Salesforce stylesheets documentation is limited (and outdated in some places). Salesforce actually discourages you from using the standard stylesheets, saying that the stylesheets are not versioned and may change without notice. I think that the styles don't change often enough to be too concerned about it, and when they do, you can quickly figure out what they changed to. If you are more paranoid than I am, you can duplicate the sfdc styles in your own CSS instead - the latest Salesforce standard stylesheets are located in the following address: https://<instance>/dCSS/Theme3/default/common.css.

Here is a simplified sample that puts it all together: