56

I have a table with 2 rows and variable columns. I tried width = 100% for the column. So the first content in the view will fit. But suppose if i am changing the contents dynamically then it is not dynamically increase/decrease the HTML table column size.

starball
  • 20,030
  • 7
  • 43
  • 238
Sonu
  • 577
  • 1
  • 4
  • 4

3 Answers3

96

If you want the cells to resize depending on the content, then you must not specify a width to the table, the rows, or the cells.

If you don't want word wrap, assign the CSS style white-space: nowrap to the cells.

Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • 6
    what if I want to have, say the first td fit the text, and the rest just even out for the width of the table? – Lucas Jan 27 '13 at 06:29
  • @think123: Sorry, I don't understand your question. Please ask a proper question with a HTML example. – Aaron Digulla Jan 27 '13 at 20:36
  • 2
    basically, I want to have the width of the table `100%`, and have every td fit its content, except for the last one, which makes up the rest of the space. Hope you can understand, as I think a question is not necessary. – Lucas Jan 27 '13 at 22:33
  • 2
    There's an answer for that here: http://stackoverflow.com/questions/8230777/how-do-i-set-the-table-cell-widths-to-minimum-except-last-column – Chris Feb 22 '13 at 17:05
  • Thank you, it took an hour of googling before I found your post and the magic white-space CSS. – Marc Clifton Oct 27 '13 at 14:23
  • WOW. This `white-space: nowrap` was exactly what I needed. Be sure to add `width: 1px` as well so that your cells are squashed. – dimiguel Aug 16 '16 at 01:09
23

You can try this:

HTML

<table>
    <tr>
        <td class="shrink">element1</td>
        <td class="shrink">data</td>
        <td class="shrink">junk here</td>
        <td class="expand">last column</td>
    </tr>
    <tr>
        <td class="shrink">elem</td>
        <td class="shrink">more data</td>
        <td class="shrink">other stuff</td>
        <td class="expand">again, last column</td>
    </tr>
    <tr>
        <td class="shrink">more</td>
        <td class="shrink">of </td>
        <td class="shrink">these</td>
        <td class="expand">rows</td>
    </tr>
</table>

CSS

table {
    border: 1px solid green;
    border-collapse: collapse;
    width:100%;
}

table td {
    border: 1px solid green;
}

table td.shrink {
    white-space:nowrap
}
table td.expand {
    width: 99%
}
Meer
  • 1,006
  • 10
  • 15
1

Well, me also I was struggling with this issue: this is how I solved it: apply table-layout: auto; to the <table> element.

vixalien
  • 347
  • 2
  • 10