我想在表格单元格中使用CSS文本溢出,这样,如果文本太长而不能适合一行,它将用省略号剪辑,而不是包装到多行。这可能吗?

我试了一下:

td {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

但是white-space: nowrap似乎使文本(及其单元格)不断向右扩展,将表的总宽度推到容器的宽度之外。但是,如果没有它,当文本到达单元格边缘时,它将继续换行为多行。


当前回答

这对我很管用

table {
    width: 100%;
    table-layout: fixed;
}

td {
   text-overflow: ellipsis;
   white-space: nowrap;
}

其他回答

为什么会发生这种情况?

似乎w3.org的这部分建议文本溢出只适用于块元素:

11.1.  Overflow Ellipsis: the ‘text-overflow’ property

text-overflow      clip | ellipsis | <string>  
Initial:           clip   
APPLIES TO:        BLOCK CONTAINERS               <<<<
Inherited:         no  
Percentages:       N/A  
Media:             visual  
Computed value:    as specified  

MDN也是这么说的。

这个jsfiddle有您的代码(带有一些调试修改),如果它应用于div而不是td,则可以正常工作。它还有我能很快想到的唯一解决方法,即将td的内容包装在包含div的块中。然而,对我来说,这看起来像是“丑陋的”标记,所以我希望其他人有更好的解决方案。测试的代码是这样的:

td, div { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; border: 1px solid red; width: 80px; } Works, but no tables anymore: <div>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</div> Works, but non-semantic markup required: <table><tr><td><div>Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah. Lorem ipsum and dim sum yeah yeah yeah.</div></td></tr></table>

在我的情况下,这是有效的,在Firefox和Chrome:

td {
  max-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
}

如果你指定table-layout: fixed;在table元素上,那么td的样式应该生效。不过,这也会影响细胞的大小。

Sitepoint在这里稍微讨论了一下表格布局方法: http://reference.sitepoint.com/css/tableformatting

我解决这个问题使用单元格内的绝对定位div(相对)。

td {
    position: relative;
}
td > div {
    position: absolute;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100%;        
}

就是这样。然后你可以添加一个top:值到div或垂直居中:

td > div {      
    top: 0;
    bottom: 0;
    margin: auto 0;
    height: 1.5em; // = line height 
}

为了在右侧获得一些空间,您可以减少max-width一点。

XML

<td><div>Your overflowing content here.</div></td>

CSS

td div
{
 max-height: 30vh;
 overflow: auto;
}

为了这个特定的目的而试图打乱整个表是没有意义的。是的,有时候如果你明确不想成为另一个600个div嵌套的Twitter/Facebook“开发者”,添加一个额外的元素是可以的。