sangil
sangil

Reputation: 1320

HTML table with auto-fit for some columns, fixed width for others

I'm trying to create a table adhering to the following requirements:

  1. The table width must be defined as 0 - the browser should calculate the width according to the column widths (this is to accommodate a column-resize plugin).
  2. Some columns may receive a fixed width (e.g. 50px);
  3. Columns that do not receive a fixed width, must auto-fit to the content.

I have created a small example to illustrate the problem - as you can see column 3 stays at width 0 and so is not visible.

EDIT: If "table-layout: fixed" is removed. the third column appears, but the fixed widths are ignored and all columns become auto-fit.

HTML

<table>
<tr>
    <td class="cell header" id="header1">Header 1</td>
    <td class="cell header" id="header2">Header 2</td>
    <td class="cell header" id="header3">Header 3</td>
</tr>
<tr>
    <td class="cell">Cell 1</td>
    <td class="cell">Cell 2</td>
    <td class="cell">Very looooong content</td>
</tr>
</table>

CSS

table {
    table-layout: fixed;
    width: 100%;
    border: 1px solid #696969;
}

.cell {
    color: #898989;
    border: 1px solid #888;
    padding: 2px;
    overflow: hidden;
}

.header {
    background-color: lightsteelblue;
    color: black;
}

#header1, #header2 {
    width: 50px;
}

Is this even possible? Any help would be appreciated...

Upvotes: 4

Views: 16611

Answers (1)

betaorbust
betaorbust

Reputation: 7978

It's not possible with table-layout: fixed and a width of 0 on your table.

Form the W3 Spec section 17.5.2.1:

In the fixed table layout algorithm, the width of each column is determined as follows:

  1. A column element with a value other than 'auto' for the 'width' property sets the width for that column.
  2. Otherwise, a cell in the first row with a value other than 'auto' for the 'width' property determines the width for that column. If the cell spans more than one column, the width is divided over the columns.
  3. Any remaining columns equally divide the remaining horizontal table space (minus borders or cell spacing).

However, when you do the automatic layout (described in section 17.5.2.2) your widths will be pushed around to work with your content and only use the widths provided when possible. For instance, if the sum of the minimum widths of each column exceeds the container width of your table, everything will get shifted around to fit independent of what widths you set.

It should be also noted that:

UAs are not required to implement this algorithm to determine the table layout in the case that 'table-layout' is 'auto'; they can use any other algorithm even if it results in different behavior.

So it looks like the answer is a unfortunately a long-winded "no" :(

Upvotes: 5

Related Questions