Search code examples
htmlcsshtml-tablewidthparent

Keep Table Cell Width fixed when inside an overflow div


Please see the code at the bottom of the post. There is a table inside a div. When the $size variable is small, like 2 or 3, and all the cells can easily fit inside the div, the width of the <th> cells are controlled correctly to have width 100px. If you change the $size variable: $size = 20, you will see that the table <th> cells are squeezed to fit in the div, even though it has an overflow:auto property. I see the same thing for overflow:scroll.

What I would like to see is the table cell width remain constant at 100px, and the div introduce a scroll bar to scroll to see all cells. I do not want the width of the cells shrinking even if the $size == 1000.

How to get the table to retain the width : 100px even though it is bigger than the parent div? And have the parent div be scroll-able then.

<style type="text/CSS">

    .headrow {
        border : 1px solid;
        width : 100px;
        height : 40px;
    }

table {
    table-layout: fixed;
}

</style>


<div id="b" style="border:1px solid;width:585px;height:60px;overflow:auto;">
    <table>
        <tr>
            <?php
            $size = 20;
                for ($i=0;$i<$size;$i++){
                    echo '<th class="headrow"></th>';
                }
            ?>
        </tr>
    </table>
</div>

Solution

  • Update your CSS to this:

    table {
        table-layout: fixed;
        width: 100%;
    }
    

    See it in action.