理解 <th> 标签的作用与默认样式
掌握 <th> 与 <td> 的区别及使用场景
熟悉 HTML5 中 <th> 支持的核心属性(如 scope、colspan、rowspan)
了解已废弃的 HTML4 属性及其现代 CSS 替代方案
能够编写语义清晰、可访问性强的表格结构
<th> 标签<th> 是 Table Header Cell(表格表头单元格) 的缩写,用于在 HTML 表格中定义列或行的标题。它通常出现在表格的第一行(列标题)或第一列(行标题)。
默认样式特点
文本加粗(bold)
内容居中对齐(center-aligned)
与普通数据单元格 <td> 形成视觉区分
这些默认样式可通过 CSS 自定义,但语义意义不变。
<table border="1">
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
<tr>
<td>张伟</td>
<td>28</td>
</tr>
</table>第一行使用
<th>定义列标题,后续行使用<td>填充数据。
推荐
<table>
<thead>
<tr>
<th>用户名</th>
<th>用户 ID</th>
</tr>
</thead>
<tbody>
<tr>
<td>李婷</td>
<td>@liting_dev</td>
</tr>
<tr>
<td>编程教程网</td>
<td>@codehub</td>
</tr>
</tbody>
</table>scope 属性详解强烈推荐使用
最佳实践:始终为 <th> 添加 scope 属性,提升无障碍体验。
<tr>
<th scope="col">产品名称</th>
<th scope="col">价格</th>
<th scope="col">库存</th>
</tr>请勿使用
以下属性在 HTML5 中已被移除,应改用 CSS 实现:
过时
<th align="left" bgcolor="#e0e0e0" width="150">姓名</th>CSS 控制
<style>
th {
text-align: left;
background-color: #f5f5f5;
width: 150px;
padding: 10px;
}
</style>
<th scope="col">姓名</th>带样式的课程成绩表
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>学生成绩表</title>
<style>
table {
border-collapse: collapse;
width: 100%;
margin: 20px auto;
}
th, td {
border: 1px solid #999;
padding: 10px;
text-align: center;
}
th {
background-color: #e6e6e6;
font-weight: bold;
}
/* 可选:斑马纹 */
tbody tr:nth-child(even) {
background-color: #fafafa;
}
</style>
</head>
<body>
<h2>期末考试成绩</h2>
<table>
<thead>
<tr>
<th scope="col">学生姓名</th>
<th scope="col">数学</th>
<th scope="col">语文</th>
<th scope="col">英语</th>
</tr>
</thead>
<tbody>
<tr>
<td>王小明</td>
<td>92</td>
<td>88</td>
<td>95</td>
</tr>
<tr>
<td>李思思</td>
<td>87</td>
<td>91</td>
<td>89</td>
</tr>
</tbody>
</table>
</body>
</html>如果一个表格既有列标题又有行标题(如左侧行名 + 顶部列名),如何正确使用 <th> 和 scope 属性?
为什么 scope 属性对视障用户特别重要?它如何影响屏幕阅读器的行为?
在响应式设计中,当表格列数过多时,如何通过 CSS 或 JavaScript 优化 <th> 的显示效果(例如固定首列或转为卡片布局)?