Tuesday, August 12, 2014

Why you should use <colgroup> to assign classes to columns

I recently stumbled upon a bug that had me baffled for a while. I had a simple label input table with the labels set to 15% width and the inputs set to 85% width. I added a class to each <td> to set the width. Everything was working great. Until it wasn't.

I noticed the columns were both at 50%. The css was still set correctly. So I started undoing my changes one by one to see what the affecting code was.

Turns out I had added a <tr> to the top of the table with colspan="2" not knowing that would affect the width of each column.

I wanted to keep that column at the top so I added a <colgroup> with the classes on each <col> instead of each <td> and voilà. Everything went back to normal.

Conclusion: When setting column classes on a table use <colgroup>

UPDATE:
I found out that only certain css properties work on <colgroups>
http://stackoverflow.com/questions/1238115/using-text-align-center-in-colgroup

So my solution is to use classes on <colgroup>s and <td>s