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

前端 未结 3 1549
北海茫月
北海茫月 2020-12-05 06:28

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 dy

相关标签:
3条回答
  • 2020-12-05 06:47

    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.

    0 讨论(0)
  • 2020-12-05 06:51

    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%
    }
    
    0 讨论(0)
  • 2020-12-05 07:05

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

    0 讨论(0)
提交回复
热议问题