HTML table, fixed width autofit columns


Is it possible to use

table-layout: fixed;
width: 100%;

On a table, yet have the columns auto size to best fit the content as a table would if not set to fixed?

The table needs to be set to fixed so it does not increase in width greater than it's parent.

Or, put differently:

Is it possible to use table-layout:auto but set a max width which will be adhered to even if a long string with no spaces is held in the table.

Best Solution

No, you cannot combine the two different table layout modes. In automatic layout (table-layout: auto, the default), the column widths are selected by the browser so that are big enough for all content in the cells; any width settings you make will be taken just as minimum widths that may make the column wider than they would otherwise be. This also means that any width setting for the table will be exceeded when necessary for the purpose. In fixed layout (table-layout: fixed), cell content is not taken into account at all. Specified widths will be used or, in the absence of width settings, the total width is divided evenly to the columns.

The conclusion is that when you want automatic layout, or “best fit”, but do not want to exceed some given limit, you need to make sure that the sum of column width requirements does not exceed it. For example, if you have a long string with no spaces, consider inserting optional line breaks at suitable places e.g. with &#x200b; or <wbr>, if the content permits breaks.

You may also consider setting a maximum width for the content of a cell. This cannot be set directly (in automatic layout), but can be done by using <td><div>…</div></td> and setting the constraint on the div. If there is e.g. a long indivisible string in the content, the content will overflow by default, but the table cell will still have width determined by the width constraint.