How to set table column widths
Short answer
Turn on table-layout: fixed and set the column widths with <col> — the browser will follow them strictly:
<style>
table { table-layout: fixed; width: 100%; border-collapse: collapse; }
td { border: 1px solid silver; padding: 6px; }
</style>
<table>
<colgroup><col style="width: 60px;"><col><col style="width: 25%;"></colgroup>
<tr><td>#1</td><td>A long product description that wraps</td><td>$25</td></tr>
<tr><td>#2</td><td>Tea</td><td>$3</td></tr>
</table>A column without a width takes all the remaining space.
Why fixed is needed
By default (table-layout: auto) the browser fits the column widths to the content, and a set width is just a wish: a long word stretches the column. In fixed mode the widths are taken from <col> or the first row and do not depend on the text — and the table renders faster too.
Truncating long text
With a fixed layout, text that does not fit can be cut off with an ellipsis:
<style>
table { table-layout: fixed; width: 260px; }
td { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
</style>
<table>
<tr><td>A very long file name that does not fit.pdf</td><td style="width: 60px;">2 MB</td></tr>
</table>Common mistake
table-layout: fixed is set, but the table itself has no width. Without width the fixed mode does not turn on, and the table adapts to the content again. Add width: 100% or an exact value.
Functions used in this recipe
- <colgroup>, <col> — Describes table columns so you can give them a width or background.
- <table> — A table made of rows (`<tr>`) and cells.
- width — The width of an element.
- text-overflow — How text that does not fit is cut: abruptly or with an ellipsis.