HTML5 中的表格(Table)是网页中展示结构化数据(如统计表、日程表、商品清单等)的重要元素。HTML 表格使用 <table>
标签定义,内部通过一系列标签组织成行和列。
下面是对 HTML5 表格语法格式的完整详解,涵盖所有核心标签、属性、示例和最佳实践。
一、HTML 表格的基本结构
<table>
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr>
<td>李雷</td>
<td>25</td>
</tr>
<tr>
<td>韩梅梅</td>
<td>24</td>
</tr>
</tbody>
</table>
说明:
<table>
:定义一个表格。<thead>
:定义表格的表头区域。<tbody>
:定义表格的主体内容。<tr>
(table row):定义一行。<th>
(table header):定义表头单元格,默认加粗并居中。<td>
(table data):定义普通单元格。
二、HTML 表格的其他重要标签
标签 | 说明 |
---|---|
<caption> | 表格标题,位于表格上方或下方。 |
<tfoot> | 表格的页脚区域,通常用于汇总信息。 |
<colgroup> | 定义一组列,可用于设置列样式。 |
<col> | 与 <colgroup> 配合,用于设置列宽、样式。 |
示例(带 <caption>
和 <tfoot>
):
<table>
<caption>员工信息表</caption>
<thead>
<tr><th>姓名</th><th>部门</th></tr>
</thead>
<tbody>
<tr><td>王强</td><td>市场部</td></tr>
<tr><td>张红</td><td>技术部</td></tr>
</tbody>
<tfoot>
<tr><td colspan="2">共计 2 名员工</td></tr>
</tfoot>
</table>
三、单元格合并(跨行/跨列)
HTML5 表格支持使用 rowspan
(跨行)和 colspan
(跨列)合并单元格。
1. 合并列(colspan)示例:
<tr>
<td colspan="2">合并两列</td>
</tr>
2. 合并行(rowspan)示例:
<tr>
<td rowspan="2">合并两行</td>
<td>内容 A</td>
</tr>
<tr>
<td>内容 B</td>
</tr>
四、表格列宽与对齐方式
可以通过 CSS 或内联属性设置列宽、文字对齐方式等。
<table border="1" style="width: 100%;">
<tr>
<th style="width: 30%; text-align: left;">商品名</th>
<th style="text-align: right;">价格</th>
</tr>
<tr>
<td>苹果</td>
<td>¥5.00</td>
</tr>
</table>
五、使用 <colgroup>
和 <col>
设置样式
<table>
<colgroup>
<col style="background-color: #f2f2f2;">
<col style="text-align: right;">
</colgroup>
<tr>
<th>产品</th>
<th>价格</th>
</tr>
<tr>
<td>橙子</td>
<td>¥3.00</td>
</tr>
</table>
六、HTML5 对表格语义的增强建议
- 使用
<caption>
增加表格标题,利于屏幕阅读器理解。 - 用
<thead>
/<tbody>
/<tfoot>
分区更清晰。 - 表头使用
<th>
,并搭配scope
属性优化辅助功能:
<th scope="col">姓名</th>
<th scope="row">项目一</th>
scope="col" | 表示该 <th> 对应列的表头 |
---|---|
scope="row" | 表示该 <th> 对应行的表头 |
七、样式美化建议(CSS 示例)
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
}
thead {
background-color: #f8f8f8;
}
tr:hover {
background-color: #f1f1f1;
}
八、注意事项与常见误区
- 表格标签不可嵌套
<table>
到<tr>
、<td>
等中(结构需闭合清晰)。 <td>
与<th>
不可直接包含块级元素(需注意兼容性)。- 表格适用于“结构化数据展示”,不应滥用来做网页布局(以前的老习惯)。
九、小结对照表
标签/属性 | 作用 |
---|---|
<table> | 定义表格 |
<tr> | 表格的一行 |
<td> | 普通单元格 |
<th> | 表头单元格 |
<caption> | 表格标题 |
<thead> | 表头区 |
<tbody> | 内容区 |
<tfoot> | 页脚区 |
rowspan | 合并行 |
colspan | 合并列 |
<colgroup> | 定义列组样式 |
scope | 辅助无障碍语义(屏读器) |
如你有特定的表格设计需求(如排班表、价格对比表、响应式表格等),我可以进一步帮你定制示例代码或样式优化方案。是否需要?
发表回复