Reputation: 23
I'm trying do to a very simple operation of merging two columns in a table. This seems easy with the colspan, but if I merge different columns without leaving at least one row without any merged columns, the sizing gets completely messed up. Please see the following example at http://www.allthingsdope.com/table.html or take a look at and try the following code:
Good:
<table width="700px">
<tr>
<th width="100px">1: 100px</th>
<td width="300px">2: 300px</td>
<td width="200px">3: 200px</td>
<td width="100px">4: 100px</td>
</tr>
<tr>
<th width="100px">1: 100px</th>
<td colspan=2 width="500px" >2 & 3: 500px</td>
<td width="100px">4: 100px</td>
</tr>
<tr>
<th width="100px">1: 100px</th>
<td width="300px">2: 300px</td>
<td colspan=2 width="300px">3 & 4: 300px</td>
</tr>
</table>
Bad:
<table width="700px">
<tr>
<th width="100px">1: 100px</th>
<td colspan=2 width="500px" >2 & 3: 500px</td>
<td width="100px">4: 100px</td>
</tr>
<tr>
<th width="100px">1: 100px</th>
<td width="300px">2: 300px</td>
<td colspan=2 width="300px">3 & 4: 300px</td>
</tr>
</table>
This seems so simple but I cannot figure it out!
Upvotes: 2
Views: 2883
Reputation: 6797
Don't put the width attribute on the individual cells. This has been deprecated since at least html 4.01 (http://www.w3.org/TR/html401/struct/tables.html#h-11.2.6, if you care that the w3c doesn't approve of your coding). In any case, you run into all sorts of troubles if you try to mix this with colspans.
Instead, add <col> elements to the table, like so:
<table width="700px">
<col width="100px"/>
<col width="300px"/>
<col width="200px"/>
<col width="100px"/>
<tr>
<th>1: 100px</th>
<td colspan="2">2 & 3: 500px</td>
<td>4: 100px</td>
</tr>
<tr>
<th>1: 100px</th>
<td>2: 300px</td>
<td colspan="2">3 & 4: 300px</td>
</tr>
</table>
The <col> element exists precisely to serve as a placeholder on which to hang attributes that apply to an entire column.
Upvotes: 2
Reputation: 4272
Just replace the width parameter in the merged column with "auto"-- it will get "whatever's left" which works out perfectly. So:
<table width="700px" border="1px">
<tr>
<th width="100px">1: 100px</th>
<td colspan=2 width="auto" >2 & 3: 500px</td>
<td width="100px">4: 100px</td>
</tr>
<tr>
<th width="100px">1: 100px</th>
<td width="300px">2: 300px</td>
<td colspan=2 width="auto">3 & 4: 300px</td>
</tr>
</table>
Upvotes: 0