I wrote a little PHP script that shows data from any table in an HTML table, and I had a little frustration in trying to keep the HTML table and column widths fixed. I wanted to do this, because I want very large tables to appear to load very quickly, and not have columns “jump” or move as additional rows are outputted to the browser. I needed to ensure the browser can determine the final width of all columns after it reads the first row in the table, and to never re-adjust it, regardless of what it finds in later rows.
I tried to control the “em” width of every column. I wanted to base the “em” width on the contents of each column. One might think this can be done by specifying a width in “em” in CSS for each <th>/</td> or <col>. Nope. I found I had to do all the following:
- In my CSS style sheet, I specify “table-layout: fixed;” for the table.
- Specify an absolute width for the overall table. By absolute, I mean anything other than “%”, which is relative to the parent width (e.g. page width). I used “em”, which has a size based on the current font size.
- Specify relative (%) widths for each column, in the CSS for each <col> tag. It’s best to use <col><colgroup> instead of styling every <th></td>.