Search code examples
htmlcsshtml-table

Why do the table column change size, and how can I stop it


I have a table with a content editable div on each row that has a colspan when you type in the content area, the 1st column shrinks in size changing the size of the div. eventually it word wraps. I don't want the layout of the table to change (horizontally). How can I prevent this?

<table style="width: 100%">
    <thead>
        <tr><th>id</th><th>Comments</th><th>Other stuff</th></tr>
    </thead>
    <tbody>
        <tr><td>1</td><td colspan="2"><div contenteditable="true" style="min-height: 1em; width: 100%; border: 1px solid red;"></div></td></tr>
        <tr><td>2</td><td colspan="2"><div contenteditable="true" style="min-height: 1em; width: 100%; border: 1px solid red;"></div></td></tr>
    </tbody>
</table>

This one without the first column doesn't do it.

<table style="width: 100%">
    <thead>
        <tr><th>Comments</th><th>Other stuff</th></tr>
    </thead>
    <tbody>
        <tr><td colspan="2"><div contenteditable="true" style="min-height: 1em; width: 100%; border: 1px solid red;"></div></td></tr>
        <tr><td colspan="2"><div contenteditable="true" style="min-height: 1em; width: 100%; border: 1px solid red;"></div></td></tr>
    </tbody>
</table>

Solution

  • The solution i am using uses points from @G-Cyr and @Amanullah Tanweer

    HTML

    <table class="has-comments">
        <thead>
            <tr><th>id</th><th>Comments</th><th>Other stuff</th></tr>
        </thead>
        <tbody>
            <tr><td>1</td><td colspan="2"><div contenteditable="true" style="min-height: 1em; width: 100%; border: 1px solid red;"></div></td></tr>
            <tr><td>2</td><td colspan="2"><div contenteditable="true" style="min-height: 1em; width: 100%; border: 1px solid red;"></div></td></tr>
        </tbody>
    </table>
    

    CSS

    table.has-comments {
        width: 100%;
    }
    

    javascript

    $("table.has-comments tr:first-child th").each(function(index){
        let element = $(this);
        let width = element.width();
        element.css("width", width + "px");
    });
    $("table.has-comments").css("table-layout", "fixed");
    

    The result is, I let the page set up the table (width 100%), then javascript/jQuery fixes column widths. Lastly the table-layout is set to fixed. It's not the most efficient solution, I know, but my page is rendered dynamically by jsp and can vary from day to day.