If I remove the width property on the table, it honours the individual
column widths. If I change the layout to table-layout: auto, then also
it works. But I just cannot get the widths to be what I want them to
be if I have a row that spans multiple columns as the first row
That is how the table-layout: fixed
works.
From here: https://developer.mozilla.org/en-US/docs/Web/CSS/table-layout
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.
And from here: https://www.w3.org/TR/CSS21/tables.html#fixed-table-layout
In this manner, the user agent can begin to lay out the table once the
entire first row has been received. Cells in subsequent rows do not
affect column widths.
So, in effect:
- If you change the layout to
auto
, it will use the automatic table layout and your column widths take precedence over the content size.
- If you remove the
width
property on a table, then it ceases to use the fixed table layout and is as good as auto
.
The other answer works because the width
property is removed (just as you mentioned in your question). If you refer back to the specs linked above, it says:
The table's width may be specified explicitly with the 'width'
property. A value of 'auto' (for both 'display: table' and 'display:
inline-table') means use the automatic table layout algorithm.
Solution:
The solution to your problem is to somehow get the table layout to ignore the first row. This is done by the colgroup
/ col
elements. Remove the classes which define the widths on the td
, and specify those on the cols
.
Snippet:
.table { table-layout: fixed; width: 100%; }
.table td, th {
border: 1px solid #aaa;
text-align: center; padding: 4px;
}
.table col.one { width: 10%; }
.table col.two { width: 20%; }
.table col.three { width: 50%; }
.table col.four { width: 20%; }
<table class="table">
<colgroup>
<col class="one"/>
<col class="two"/>
<col class="three"/>
<col class="four"/>
</colgroup>
<tbody>
<tr><th colspan="4">All Four</th></tr>
<tr><th colspan="4">All Four</th></tr>
<tr>
<td >A</td>
<td >B</td>
<td >C</td>
<td >D</td>
</tr>
</tbody>
</table>