Search code examples
htmlmergehtml-tablewidthcell

Having two html table cells total width stay within given width?


I have an html table using colspan=2 to merge cells. I need to make sure merged cells have a given width. However, when two cells are not merged, I need to have their total width not exceed the width of the merged cells. How can I achieve the latter?

enter image description here

In the first table, the text in the merged cells is wrapped, which is fine.

In the second table, the text in the non-merged cells is not wrapped, which makes the table too wide.

I have created a JSFiddle.

My html is:

<table border="1">
    <tr>
        <td>xyz 1</td>  
        <td>xyz 2</td>  
        <td>xyz 3</td>  
        <td>xyz 4</td>  
    </tr>
    <tr>
        <td colspan="2" class="twoColWidth">
            xyz aaaa ffffffffffffff
        </td>  
        <td colspan="2" class="twoColWidth">
            xyz bbbb fff
        </td>  
    </tr>
</table>
<br />
<table border="1">
    <tr>
        <td>xyz 1 33333 444444</td>  
        <td>xyz 2</td>  
        <td>xyz 3</td>  
        <td>xyz 4 33333 444444</td>  
    </tr>
    <tr>
        <td colspan="2" class="twoColWidth">
            xyz aaaa ffffffffffffff
        </td>  
        <td colspan="2" class="twoColWidth">
            xyz bbbb fff
        </td>  
    </tr>
</table>

and my CSS is:

.twoColWidth {
    width: 50px;
}

Solution

  • Give your table a fix width, and use colgroup with col to give all the columns the same width:

    <table border="1" style="width: 175px;">
        <colgroup>
            <col span="4" width="25%" />
        </colgroup>
        <tr>
            <td>xyz 1</td>  
            <td>xyz 2</td>  
            <td>xyz 3</td>  
            <td>xyz 4</td>  
        </tr>
        <tr>
            <td colspan="2">
                xyz aaaa ffffffffffffff
            </td>  
            <td colspan="2">
                xyz bbbb fff
            </td>  
        </tr>
    </table>