我一直在使用word-wrap: break-word在div和span中对文本进行换行。然而,它似乎在表格单元格中不起作用。我有一个设置为width:100%的表,有一行和两列。列中的文本虽然使用了上面的换行样式,但不能自动换行。它会导致文本超出单元格的边界。这发生在Firefox,谷歌Chrome和Internet Explorer上。

下面是源代码的样子:

td { 边框:1px实体; L} <table style="width: 100%;"> < tr > < td > < span style=" font - family:宋体;"> Looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong词 < / div > 道明> < / <span style=" font - family:宋体;">短字< / span > < / td > < / tr > 表> < /

上面的长单词比我的页面的边界大,但它没有与上面的HTML中断。我尝试了以下添加文本换行:抑制和文本换行:正常的建议,但都没用。


当前回答

<p style="overflow:hidden; width:200px; word-wrap:break-word;">longtexthere<p>

其他回答

我也遇到过类似的问题。我在一个AngularJS应用程序的Bootstrap模式中有一个表。当我更改表上的过滤器,并且在相关单元格中出现长值时,文本将溢出到单元格之外和模态之外。这个CSS最终解决了这个问题,应用到TD上:

style="white-space:pre-wrap; word-break:break-word"

这使得值即使在更改表内容时也能正确地换行。

事实证明,这并没有什么好办法。我最接近的做法是在表格周围的div中添加“overflow:hidden;”,从而丢失文本。 真正的解决办法似乎是抛弃餐桌。使用divs和相对定位,我能够实现相同的效果,减去<table>的遗留

2015更新:这是为那些像我一样想要这个答案的人准备的。经过6年的努力,感谢所有贡献者。

* { /* this works for all but td */
  word-wrap:break-word;
}

table { /* this somehow makes it work for td */
  table-layout:fixed;
  width:100%;
}

获得奖励的答案是正确的,但如果表的第一行有一个合并/连接的单元格(所有单元格的宽度相同),它就不起作用。

在这种情况下,你应该使用colgroup和col标签来正确显示它:

<table style="table-layout: fixed; width: 200px">
<colgroup>
    <col style="width: 30%;">
    <col style="width: 70%;">
</colgroup>
<tr>
    <td colspan="2">Merged cell</td>
</tr>
<tr>
    <td style="word-wrap: break-word">VeryLongWordInThisCell</td>
    <td style="word-wrap: break-word">Cell 2</td>
</tr>
</table>

如果你不需要表格边框,应用这个:

table{
    table-layout:fixed;
    border-collapse:collapse;
}
td{
    word-wrap: break-word;
}

下面是我在ie浏览器中使用的。注意添加了table-layout:fixed CSS属性

td { 边框:1px实体; } <table style=" font - family:宋体;宽度:100%”> < tr > < span style=" font - family:宋体 LongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongLongWord 道明> < / < / tr > 表> < /