CSS table td width - fixed, not flexible

后端 未结 8 1704
温柔的废话
温柔的废话 2020-12-12 19:55

I have a table and I want to set a fixed width of 30px on the td\'s. the problem is that when the text in the td is too long, the td is stretched out wider than 30px.

8条回答
  •  春和景丽
    2020-12-12 20:04

    It is not only the table cell which is growing, the table itself can grow, too. To avoid this you can assign a fixed width to the table which in return forces the cell width to be respected:

    table {
      table-layout: fixed;
      width: 120px; /* Important */
    }
    td {
      width: 30px;
    }
    

    (Using overflow: hidden and/or text-overflow: ellipsis is optional but highly recommended for a better visual experience)

    So if your situation allows you to assign a fixed width to your table, this solution might be a better alternative to the other given answers (which do work with or without a fixed width)

提交回复
热议问题