必须设置 table-layout: fixed 且用 <col> 的 CSS width(如 style="width:30%;")才能稳定实现百分比列宽,仅设 <td> width 或用 HTML width 属性均无效;需配合 white-space: nowrap 和 overflow: hidden 防内容撑宽。
直接用 table-layout: fixed + <col> 设置 CSS width 就能稳定实现列宽百分比分配,其他方式(比如只给 <td> 加 width: 30%)在内容较长时大概率失效。
table-layout: fixed
表格默认是 table-layout: auto,浏览器会扫描全部内容再算列宽,你写的 width 会被无视。只有设成 fixed,列宽才按你定义的走。
table 元素上必须加 style="table-layout: fixed; width: 100%;"(width 值不一定是 100%,但要有明确值)div 没设 width),百分比列宽会计算失败width 属性(如 <table width="100%">),它和 CSS width 不等价,且已过时<col> 的 width 必须是 CSS 属性,不是 HTML 属性<col width="30%"> 完全无效 —— 这是 HTML 属性,浏览器忽略。必须写成 <col style="width: 30%;"> 或用外部 CSS 选择器匹配。
<colgroup> 里,语义清晰:<colgroup><col style="width: 25%;"><col style="width: 50%;"></colgroup>
<th> 或 <td> 不能设 width,否则会覆盖 <col> 定义white-space: nowrap 和 overflow: hidden
即使用了 table-layout: fixed,长文本仍可能触发换行或溢出,导致视觉上“列变宽”。这不是布局失效,而是内容渲染行为。
立即学习“前端免费学习笔记(深入)”;
<td> 和 <th> 统一加 white-space: nowrap; overflow: hidden;
text-overflow: ellipsis;(注意要同时设 display: block 或 inline-block)box-sizing: border-box;
<col> 能不能做?可以,但更难控直接给 <th>/<td> 设 width: 30% 看似简单,但实际效果取决于第一行内容长度 —— 浏览器仍会按 auto 模式部分介入计算。
<col> + fixed 是唯一可靠路径<col> 支持有限,但现代项目基本无需兼容真正卡住人的不是语法,而是忘记 table-layout: fixed 这个前提,或者把 HTML width 属性当成 CSS 用。只要这两点踩准,列宽百分比就是确定性行为,不看内容、不猜浏览器。