HTML Table - Both fixed and multiple variable column widths

Basaa picture Basaa · Feb 8, 2014 · Viewed 41.9k times · Source

I have to build a table with 5 columns. The table width is variable (50% of content width). Some columns contain fixed-size buttons, so those columns should have a fixed with, say 100px. Some columns have text in them, so I want those columns to have variable column widths.

For example:

Column1: 20% of (tablewidth - sum(fixedwidth_columns))'

Column2: 100px

Column3: 40% of (tablewidth - sum(fixedwidth_columns))

Column4: 200px

Column5: 40% of (tablewidth - sum(fixedwidth_columns))

What is the best way to achieve this?

Answer

Hashem Qolami picture Hashem Qolami · Feb 8, 2014

You could set the table-layout: fixed for the table element, then simply set width attribute on relevant <td> or <th> elements:

table {
    table-layout: fixed;
}

JSFiddle Demo.

From the MDN:

The table-layout CSS property defines the algorithm to be used to layout the table cells, rows, and columns.

Values:

fixed:
Table and column widths are set by the widths of table and col elements or by the width of the first row of cells. Cells in subsequent rows do not affect column widths.