今日升级技能
掌握表格的进阶用法,让你的数据展示更专业!本节重点学习:
- 语义化表头 <th>
- 表格标题 <caption>
- 单元格合并技巧 colspan/rowspan
完整表格结构示例
<table>
<caption>公司部门信息表</caption> <!-- 表格的标题 -->
<thead> <!-- 表头区 -->
<tr>
<th rowspan="2">部门</th> <!-- 纵向合并 -->
<th colspan="2">人员统计</th> <!-- 横向合并 -->
</tr>
<tr>
<th>员工数</th> <!-- 次级表头 -->
<th>平均工龄</th>
</tr>
</thead>
<tbody> <!-- 数据区 -->
<tr>
<th>技术部</th> <!-- 行表头 -->
<td>42</td>
<td>3.5年</td>
</tr>
</tbody>
</table>
核心特性详解
1. 语义化表头 <th>
- 默认样式:加粗+居中
- 两种用法:
<!-- 列表头 -->
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
<!-- 行表头 -->
<tr>
<th>技术部</th>
<td>42人</td>
</tr>
2. 表格标题 <caption>
- 必须紧接<table>之后
- 屏幕阅读器会优先朗读
- 样式控制示例:
caption {
caption-side: bottom; /* 可置顶(top)或置底(bottom) */
font-weight: bold;
padding: 10px;
}
3. 单元格合并黑科技
属性 | 效果 | 使用场景 |
---|---|---|
colspan="2" | 合并右侧单元格 | 创建跨列标题 |
rowspan="3" | 合并下方单元格 | 创建垂直标题 |
合并技巧口诀:
"col横着走,row竖着来,合并之后要减格"
实战技巧
复杂表头设计
<tr>
<th rowspan="2">季度</th>
<th colspan="3">产品线</th>
</tr>
<tr>
<!-- 注意:因为第一列已rowspan,这里只有3个th -->
<th>手机</th>
<th>笔记本</th>
<th>配件</th>
</tr>
响应式表格优化
@media (max-width: 600px) {
table, thead, tbody, th, td, tr {
display: block; /* 小屏时转为块级显示 */
}
th {
position: absolute; /* 隐藏表头 */
left: -9999px;
}
}
高级避坑指南
合并单元格计算器:合并后要删除被占用的<td>,比如:
<!-- 错误示例 -->
<tr>
<td colspan="2">合并格</td>
<td>多余的格子</td> <!-- 这会使表格变形! -->
</tr>
辅助技术友好性:
<th scope="col">姓名</th> <!-- 列标题 -->
<th scope="row">技术部</th> <!-- 行标题 -->
打印优化
@media print {
table { page-break-inside: avoid; } /* 避免表格跨页断开 */
}
创意应用场景
日历设计:
<table>
<caption>2023年10月</caption>
<tr><th>日</th><th>一</th>...<th>六</th></tr>
<tr><td>1</td><td>2</td>...<td>7</td></tr>
</table>
- 象棋棋盘:
<table class="chess-board">
<tr>
<td></td><th scope="col">A</th>...<th scope="col">H</th>
</tr>
<tr><th scope="row">8</th><td></td>...<td></td></tr>
<!-- 更多行... -->
</table>
记住:高级表格就像乐高,用<th>
搭建框架,用合并创造形态,用caption
讲述故事。当普通表格不能满足你时,这些特性就是你的瑞士军刀!就像程序员用表格排bug——虽然最后可能排出一个更大的bug。