Freezing columns in an HTML table

I am trying to do a very simple merge operation of two columns in a table. It seems lightweight with colspan, but if I concatenate different columns without leaving at least one row without any concatenated columns, the size gets completely messed up. Please see the following example http://www.allthingsdope.com/table.html or see the following code:

Okay:

<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>

      

It seems so simple, but I can't figure it out!

+2


a source to share


2 answers


Don't put the width attribute in separate 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 are embarrassed that w3c doesn't approve of your encoding). Either way, you run into all the trouble if you try to mix this with colspans.

Instead, add <col> elements to the table, for example:



    <table width="700px">
        <col width="100px"/>
        <col width="300px"/>
        <col width="200px"/>
        <col width="100px"/>
        <tr>
            <th>1: 100px</th>
            <td colspan="2">2 &amp; 3: 500px</td>
            <td>4: 100px</td>
        </tr>
        <tr>
            <th>1: 100px</th>
            <td>2: 300px</td>
            <td colspan="2">3 &amp; 4: 300px</td>
        </tr>
    </table>

      

The <col> element exists precisely to serve as a placeholder from which to hang attributes that apply to the entire column.

+2


a source


Just replace the width parameter in the merged column with "auto" - it will get "everything else", which works great. 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>

      

0


a source







All Articles