You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为什么相同样式下text-overflow: ellipsis在table中不生效

问题根因
  • 表格默认布局规则限制:<table> 元素默认的 table-layout 属性值为 auto,该模式下表格总宽度会根据单元格内容自动计算,你设置在 <tr>、<td> 上的宽度会被过长内容撑开,无法按照设定值生效。
  • 宽度设置位置错误:你仅给 <tr> 设置了 width="100px",没有给 <table> 本身设置固定宽度,表格自身没有宽度限制,自然会跟随内容延伸。
  • 单元格属性生效依赖:<td> 作为表格单元格元素,overflow: hidden、text-overflow: ellipsis 要生效,必须依赖表格的固定布局模式。
修复方案

给 <table> 元素添加固定宽度和 table-layout: fixed 属性即可达到和 div 一致的省略号效果,修正后的完整代码如下:

.container { 
  display: flex; 
  flex-direction: row; 
} 
/* 新增table样式规则 */
table {
  width: 100px;
  table-layout: fixed;
}
p, td { 
  white-space: nowrap; 
  overflow: hidden; 
  text-overflow: ellipsis; 
}
<div class="container" style="width:100px; background-color: red">
  <p width="50px"> Hello world </p>
  <p width="50px"> Hello world </p>
</div>
<table style="background-color: green">
  <tr width="100px">
    <td width="50px">Hello World</td>
    <td width="50px">Hello World</td>
  </tr>
</table>

内容的提问来源于stack exchange,提问作者Alimur Razi Rana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 01:18:00