CSS table td width - fixed, not flexible

2019-01-21 05:31发布

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. Overflow:hidden doesnt work either on the td's, I need some way of hiding the overflowing text and keeping the td width 30px.

<table cellpadding="0" cellspacing="0">
    <tr>
        <td>first</td><td>second</td><td>third</td><td>forth</td>
    </tr>
    <tr>
        <td>first</td><td>this is really long</td><td>third</td><td>forth</td>
    </tr>
</table>

标签: html css Table
8条回答
你好瞎i
2楼-- · 2019-01-21 06:12

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)

查看更多
女痞
3楼-- · 2019-01-21 06:12

The above suggestions trashed the layout of my table so I ended up using:

td {
  min-width: 30px;
  max-width: 30px;
  overflow: hidden;
}

This is horrible to maintain but was easier than re-doing all the existing css for the site. Hope it helps someone else.

查看更多
登录 后发表回答