CSS / 参考 / caption-side:设置表格标题的位置
CSS 的 caption-side 将 HTML 表格的 <caption> 放在数据区域上方或下方。初始值为 top,需要放在行下方时用 bottom。无论显示在哪一侧,标题都放在 <table> 的第一个子元素位置。
将表格标题放在上方或下方
横排时,top 把标题放在表头和数据行上方,bottom 把它放在最后一行下方。该属性适用于 table-caption 盒,并且可以继承。因此,给表格设置位置也可以作用到它的标题。各值见 CSS 标题位置规范。
table.sales { caption-side: bottom; }
table.sales > caption { text-align: start; padding-block: .45em; }
选择器 .sales 把规则限定在目标表格上,避免其他表格也受到通用 bottom 规则的影响。请在标题上另行设置文字对齐和间距。
在页面上比较两个位置
两个表格的数据和标题相同。第一个的标题在列标题上方,第二个的标题在最后一行下方。移动标题时,月份顺序和对应数量保持原样。
caption-side: top
| 月份 | 数量 |
|---|---|
| 一月 | 12 |
| 二月 | 18 |
caption-side: bottom
| 月份 | 数量 |
|---|---|
| 一月 | 12 |
| 二月 | 18 |
运行示例并检查 HTML 结构
将完整文档以 UTF-8 编码保存为 caption-side-example.html 并在浏览器中打开。示例不需要外部样式表。第一个表格使用初始位置,第二个带有 .below 类。
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>比较 CSS caption-side 的值</title>
<style>
body { margin: 1rem; color: #20242b; background: #fff;
font: 1rem/1.5 system-ui, sans-serif; }
main { max-width: 42rem; margin-inline: auto; }
.examples { display: grid; gap: 1rem;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 13rem), 1fr)); }
table.sales { width: 100%; border-collapse: collapse; }
table.sales.below { caption-side: bottom; }
table.sales > caption { font-weight: 650; padding-block: .45em;
text-align: start; overflow-wrap: anywhere; }
td, th { border: 1px solid #647681; padding: .45rem .6rem; }
th { text-align: start; }
td { text-align: end; }
thead { background: #e6f1f7; }
</style>
</head>
<body>
<main>
<h1>比较 CSS caption-side 的值</h1>
<div class="examples">
<div>
<p><code>top</code></p>
<table class="sales above">
<caption>每月销售数量</caption>
<thead><tr><th scope="col">月份</th><th scope="col">数量</th></tr></thead>
<tbody>
<tr><th scope="row">一月</th><td>12</td></tr>
<tr><th scope="row">二月</th><td>18</td></tr>
</tbody>
</table>
</div>
<div>
<p><code>bottom</code></p>
<table class="sales below compact">
<caption>每月销售数量</caption>
<thead><tr><th scope="col">月份</th><th scope="col">数量</th></tr></thead>
<tbody>
<tr><th scope="row">一月</th><td>12</td></tr>
<tr><th scope="row">二月</th><td>18</td></tr>
</tbody>
</table>
</div>
</div>
</main>
</body>
</html>
只把 table.sales.below 规则中的 bottom 换成 top,然后刷新。第二个标题移到表格上方,行顺序维持原样。检查完再改回 bottom。
用 <caption> 提供描述数据的简短标题。无论标题是否显示在数据下方,在源码中都放在 thead 前。这样标题就与表格关联。第一个子元素的规则见 HTML caption 元素规范。
调整标题的对齐、间距和换行
标题移到所需的一侧后,用 text-align 设置内部的文字对齐。横排时,start 对齐到书写方向的起始端,center 使文字居中。padding-block 在文字上下留出间距。设置在 td 或 th 上的对齐用于单元格内容。
想观察长标题如何换行,可以增加标题文字并缩窄窗口。对于必须放得下的无空格长字符串,可以像示例一样用 overflow-wrap: anywhere。竖排时,请在实际书写模式和浏览器中检查位置。表格与列的宽度见 CSS 表格尺寸指南。
排查标题位置没有变化的原因
在开发者工具中选中 caption,检查 caption-side 和 display 的计算值。该属性要求 table-caption 盒。如果表格声明了 bottom 但标题仍在上面,查找直接应用在标题上的声明。
table.sales.compact > caption {
caption-side: top;
text-align: center;
}
将上面的规则加到示例样式表的末尾。直接设置的 top 会覆盖从第二个表格继承的 bottom。删掉 text-align: center 可分别验证两项设置。标题仍在上方,文字重新对齐到起始端。



