How to Auto resize HTML table cell to fit the text size

HtmlCss

Html Problem Overview


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. Thanks in advance.

Html Solutions


Solution 1 - Html

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.

Solution 2 - Html

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%
}

Solution 3 - Html

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSonuView Question on Stackoverflow
Solution 1 - HtmlAaron DigullaView Answer on Stackoverflow
Solution 2 - HtmlMeerView Answer on Stackoverflow
Solution 3 - HtmlvixalienView Answer on Stackoverflow