许多人仍然使用表格来布局控件、数据等--流行的jqGrid就是一个例子。然而,有一些魔术发生了,我似乎无法理解(它的桌子大声喊叫,可能有多少魔法?)
如何能够设置表的列宽,并像jqGrid那样遵从它?如果我试图复制这个,即使我设置<td style='width: 20px'>
,当其中一个单元格的内容大于20 px时,该单元格就会扩展!
可以尝试使用<col>
标记管理所有行的表样式,但需要设置table-layout:fixed
上的样式<table>
类和overflow
单元格样式
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/col
<table class="fixed"> <col width="20px" /> <col width="30px" /> <col width="40px" /> <tr> <td>text</td> <td>text</td> <td>text</td> </tr> </table>
这就是你的CSS
table.fixed { table-layout:fixed; } table.fixed td { overflow: hidden; }
现在在HTML 5/CSS 3中,我们有了更好的解决方案。在我看来,这个纯粹的CSS解决方案是建议的:
table.fixed {table-layout:fixed; width:90px;}/*Setting the table width is important!*/ table.fixed td {overflow:hidden;}/*Hide text outside the cell.*/ table.fixed td:nth-of-type(1) {width:20px;}/*Setting the width of column 1.*/ table.fixed td:nth-of-type(2) {width:30px;}/*Setting the width of column 2.*/ table.fixed td:nth-of-type(3) {width:40px;}/*Setting the width of column 3.*/
<table class="fixed"> <tr> <td>Veryverylongtext</td> <td>Actuallythistextismuchlongeeeeeer</td> <td>We should use spaces tooooooooooooo</td> </tr> </table>
只需像这样修改代码:
table.fixed { table-layout:fixed; width:90px; word-break:break-all;}