Question

When I have a table inside a div and if the width of the table is bigger than the div, the table will automatically resize all its cells to match, even if the cells have width explicitly set.

I have this fiddle to demonstrate. Note that the table cells have a 900px width defined in CSS but the table still shrinks them to fit its parent's width.

But my desired effect is to let the table's width depend on only the width of the table cells (in the mean time have a min-width to fill the parent), but still be contained within a parent with overflow: scroll so the table would overflow and the user can scroll.

So in short: container has fixed width, table has dynamic width depending on table cells' width.

Was it helpful?

Solution

I think this is what you are after:

table { 
    border-collapse:separate; 
    border-top: 3px solid grey;
    min-width: 100%;
}

This...

  • Makes the table the width of the container
  • Allows the table to expend to a size larger than the container
  • Results in scroll bars if the width is greater than the container

This doesn't force the cells to be 900px despite not having content, you could force this by wrapping the cell contents in an element with a minimum width:

<div class="container">
    <table>
        <tr>
            <td class="headcol">1</td>
            <td class="long">ZOMG</td>
            <td class="long"><div>ZOMG</div></td>
        </tr>
    </table>
</div>

CSS

table { 
    border-collapse:separate; 
    border-top: 3px solid grey;
    table-layout: fixed;
}

td {
    margin:0;
    border:3px solid grey; 
    border-top-width:0px; 
    white-space:nowrap;
}

.container { 
    width: 600px; 
    overflow-x:scroll;  
    overflow-y:visible;
    border: 1px solid red;
    padding: 10px;
}

.long { 
    background:yellow; 
    letter-spacing:1em; 
    display: 
}

.long div {
    min-width: 900px;   
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top