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

前端 未结 7 1506
独厮守ぢ
独厮守ぢ 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

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

    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;
    }
    element1 data junk here which can span multiple lines last column, minimum width, one line
    elem more data other stuff again, last column
    more of these rows

提交回复
热议问题