Table Layout Trick
Generally, browsers determine the width of table columns by the contents within the columns.
You may have noticed table columns changing width while a table is being loaded. The browser determines a new width for a column as it encounters content to be displayed within that column.
But what if each column needs to be a specific width? In that case, do two things:
-
Use the CSS
table-layout:fixed;
declaration within thetable
tag. -
In the first row of the table, specify the width of the columns.
Here is a table to illustrate. Each column is specified to be 100 pixels wide.
Blue | White, Blue, and Green |
Orange | Red, Orange, and Yellow |
Telling the browser that the table layout is fixed means it does not have to spend time calculating widths for the table past the first row. The page is then in position to render more quickly. And, you have control over the width of table columns.
Here is the source code for the above table.
<table border="1" cellpadding="0" cellspacing="0" style="table-layout:fixed; border:1px solid black;"> <tr> <td style="width:100px;">Blue</td> <td style="width:100px;">White, Blue, and Green</td> </tr> <tr> <td>Orange</td> <td>Red, Orange, and Yellow</td> </tr> </table>
The table-layout:fixed;
declaration in the table tag tells the browser that the table columns should not be adjusted after the first row.
The width:100px;
in each td
tag of the first row tells the browser how wide the columns should be.
The rest of the table, one more row in this case but however many rows the table might have, should conform to the column width specifications found in the first row.
It is indeed possible to have tables with column widths that you specify.
(This content first appeared in Possibilities newsletter.)
Will Bontrager