Character alignment with align="char" finally works in HTML tables!

I know, every single page on the interweb talks about char and charoff being valid attributes. But they don't work in browsers at the moment (November 2006). Let's add the functionality with JavaScript then :]

Basic table

Number Description Costs
1 Lorem ipsum dolor sit amet $3,99
2 Consectetuer adipiscing elit $13,95
3 Pellentesque fringilla nisl ac mi $4
4 Aenean egestas gravida magna $123,999

The same table, with align="char" and char=","; does it work in your browser?

Number Description Costs
1 Lorem ipsum dolor sit amet $3,99
2 Consectetuer adipiscing elit $13,95
3 Pellentesque fringilla nisl ac mi $4
4 Aenean egestas gravida magna $123,999

A quick fix with CSS and floating spans

Number Description Costs
1 Lorem ipsum dolor sit amet $3,99
2 Consectetuer adipiscing elit $13,95
3 Pellentesque fringilla nisl ac mi $4
4 Aenean egestas gravida magna $123,999
td.char-align { width: 7em; }
span.left { float: left; text-align: right; width: 4em; }
span.right { float: right; width: 3em; text-align: left; }

Problems and things to keep in mind

Well, the widths are needed, but shouldn't be hardcoded in the stylesheet (although they could be). Also, the spans aren't needed in the actual markup (they are in the DOM).

According to the HTML specification, the order of precedence (from highest to lowest) for the attributes align, char, and charoff is the following:

  1. An alignment attribute set on an element within a cell's data (e.g., P).
  2. An alignment attribute set on a cell (TH and TD).
  3. An alignment attribute set on a column grouping element (COL and COLGROUP). When a cell is part of a multi-column span, the alignment property is inherited from the cell definition at the beginning of the span.
  4. An alignment attribute set on a row or row grouping element (TR, THEAD, TFOOT, and TBODY). When a cell is part of a multi-row span, the alignment property is inherited from the cell definition at the beginning of the span.
  5. An alignment attribute set on the table (TABLE).
  6. The default alignment value.

The align="char" thingy can be put on a TD, TH, COL, COLGROUP, TR, THEAD, TFOOT and TBODY element.

I think it's handy to put it on a COL element.

So now with some unobtrusive JavaScript magic

Number Description Costs
1 Lorem ipsum dolor sit amet $3.99
2 Consectetuer adipiscing elit $13.95
3 Pellentesque fringilla nisl ac mi $4
4 Aenean egestas gravida magna $3,423.999

And another one, with Dutch numbers

Number Description Costs
1 Lorem ipsum dolor sit amet €3,99
2 Consectetuer adipiscing elit €13,95
3 Pellentesque fringilla nisl ac mi €4,-
4 Aenean egestas gravida magna €3.423,999

Or you can just hardcode the characters in JavaScript


Home - More stuff