el_shayan
el_shayan

Reputation: 2845

Change width of TABLE based on its TD cells

I am looking for a way to specify a table's width by specifying widths of its TDs.

In the following scenario (try it live on jsfiddle) you can see that I have specified width of each TD as 100px and I expected to get a 300px table (and a horizontal scrollbar for div) but in practice browsers give them a width of 63px (that's table's width divided by 3)

wrong width

Is there any way to make TDs determine the width of table and not other way round? So far I have tried different values of table-layout, display, overflow for TD and TABLE without any success.

The html:

<div>
    200px
    <table>
        <tr>
            <td>100px</td>
            <td>100px</td>
            <td>100px</td>
        </tr>
    </table>
</div>

and a minimal CSS:

div {
    width: 200px; 
    height: 300px; 
    border: solid 1px red; 

    overflow-x: scroll;
}

td {
    width:100px; 
    border: solid 1px #000;
}

table { 
    border-collapse: collapse;
}

Upvotes: 2

Views: 1190

Answers (3)

el_shayan
el_shayan

Reputation: 2845

Simplest solution appears to be setting min-width instead of width for TDs.

Upvotes: 3

user1618143
user1618143

Reputation: 1748

If you're dynamically generating the table, you could just dynamically set the width of the table while you're at it. Just calculate the desired width, and add style="width:300px;" (or whatever) to the <table> tag.

Not that the other options people have posted here aren't also perfectly valid, of course.

Upvotes: 0

meub
meub

Reputation: 2318

A simple solution is make the td's content be 100px wide.

<div>
    200px
    <table>
        <tr>
            <td><div class="content">100px</div></td>
            <td><div class="content">100px</div></td>
            <td><div class="content">100px</div></td>
        </tr>
    </table>
</div>

.content {
    width: 100px;
}

Upvotes: 3

Related Questions