How do I set the table cell widths to minimum except last column?

前端 未结 7 1377
独厮守ぢ
独厮守ぢ 2020-12-07 11:44

I have a table with 100% width. If I put s in it, they get spread out with equal length columns. However, I want all the columns except last to have a

相关标签:
7条回答
  • 2020-12-07 12:16

    Slightly different topic but maybe it helps someone who stumbles on this question like me.
    (I just saw the comment by Campbeln who suggests exactly this after writing my answer below, so this is basically a detailed explanation of his comment)

    I had the problem the other way around: I wanted to set one table column to the minimum width possible without breaking it on white space (last column in the following example) but the other's width should be dynamic (including line breaks):

    -----------------------------------------------------------------------------------
    element1 | data      | junk here which can   | last column, minimum width, one line
                           span multiple lines
    -----------------------------------------------------------------------------------
    elem     | more data | other stuff           | again, last column
    -----------------------------------------------------------------------------------
    more     | of        | these                 | rows
    -----------------------------------------------------------------------------------
    

    Simple solution:

    HTML

    <table>
      <tr>
        <td>element1</td>
        <td>data</td>
        <td>junk here which can span multiple lines</td>
        <td class="shrink">last column, minimum width, one line</td>
      </tr>
      <tr>
        <td>elem</td>
        <td>more data</td>
        <td>other stuff</td>
        <td class="shrink">again, last column</td>
      </tr>
      <tr>
        <td>more</td>
        <td>of</td>
        <td>these</td>
        <td class="shrink">rows</td>
      </tr>
    </table>
    

    CSS

    td.shrink {
      white-space: nowrap;
      width: 1px;
    }
    

    Columns with class shrink only expand to the minimum width but others stay dynamic. This works because width of td is automatically expanded to fit whole content.

    Example Snippet

    table {
      width: 100%;
    }
    
    td {
      padding: 10px;
    }
    
    td.shrink {
      white-space: nowrap;
      width: 1px;
    }
    <table>
      <tr>
        <td>element1</td>
        <td>data</td>
        <td>junk here which can span multiple lines</td>
        <td class="shrink">last column, minimum width, one line</td>
      </tr>
      <tr>
        <td>elem</td>
        <td>more data</td>
        <td>other stuff</td>
        <td class="shrink">again, last column</td>
      </tr>
      <tr>
        <td>more</td>
        <td>of</td>
        <td>these</td>
        <td class="shrink">rows</td>
      </tr>
    </table>

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