CSS empty-cells:如何显示或隐藏空单元格的边框
创建时间 2026-11-22
最后修改 2026-11-22
当表格使用 border-collapse: separate 时,CSS empty-cells 决定是否绘制空单元格的边框和背景。show 会绘制,hide 会隐藏。单元格本身仍保留在 HTML 中。
设置空单元格的边框和背景
初始值是 show。该属性可以继承,通常在表格上统一设置,再为需要显示的单元格指定 empty-cells: show。
使用 border-collapse: collapse 时,相邻单元格共享边框,empty-cells 不影响绘制。同行其他单元格有内容时,该行仍占空间。整行为空时,高度可能不同。
.demo { border-collapse: separate; empty-cells: hide; }
在相同的表格上比较 show 和 hide
将完整代码以 UTF-8 编码保存为 empty-cells-example.html,然后在浏览器中打开。两张表只有 empty-cells 的值不同。
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>比较空单元格</title>
<style>
body { margin: 1rem; font: 1rem/1.5 system-ui, sans-serif; }
.samples { display: flex; flex-wrap: wrap; gap: 1rem; }
.demo {
border-collapse: separate;
border-spacing: 4px;
background: #dbeafe;
}
.demo.show { empty-cells: show; }
.demo.hide { empty-cells: hide; }
.demo th, .demo td {
border: 1px solid #334155;
background: #fef3c7;
padding: .5rem;
}
.demo td { min-width: 3.5rem; }
.demo caption { text-align: start; }
</style>
</head>
<body>
<h1>比较空单元格</h1>
<div class="samples">
<table class="demo show">
<caption>empty-cells: show</caption>
<thead><tr><th scope="col">项目</th><th scope="col">数量</th></tr></thead>
<tbody>
<tr><th scope="row">零件 A</th><td class="blank"></td></tr>
<tr><th scope="row">零件 B</th><td>18</td></tr>
</tbody>
</table>
<table class="demo hide">
<caption>empty-cells: hide</caption>
<thead><tr><th scope="col">项目</th><th scope="col">数量</th></tr></thead>
<tbody>
<tr><th scope="row">零件 A</th><td class="blank"></td></tr>
<tr><th scope="row">零件 B</th><td>18</td></tr>
</tbody>
</table>
</div>
</body>
</html>
第一张表的空数量单元格有黄色背景和边框。第二张表的同一位置露出蓝色表格背景。两张表都保留原有的行和列。
测试空格和边框模型
- 在第二张表的空单元格中插入一个普通空格。默认的空白折叠会去掉它,单元格仍按空白处理。
- 将其替换为
。这个不换行空格不会被折叠掉,于是黄色背景和边框会出现。比较后将其删除。 - 将两张表的
border-collapse都改成collapse。两个空单元格都会绘制背景,比较后恢复separate。
排查空单元格仍显示的原因
在开发者工具中检查表格的 border-collapse 和单元格的 empty-cells 计算值。排查不换行空格、行内子元素和生成内容。
隐藏单元格的背景后,仍可能看到表格自身的背景。表格外边框和单元格间距需分别设置。若缺失的信息有明确含义,可以写明“不适用”,使读者理解其原因。



