表格是 HTML 中用于展示结构化数据的重要元素。
<table>
<tr>
<th>标题1</th>
<th>标题2</th>
</tr>
<tr>
<td>数据1</td>
<td>数据2</td>
</tr>
</table>
<table> - 表格容器定义整个表格
<table border="1">
<!-- 表格内容 -->
</table>
<tr> - 表格行定义表格中的一行
<tr>
<td>单元格1</td>
<td>单元格2</td>
</tr>
<td> - 表格数据单元格定义标准数据单元格
<td>单元格内容</td>
<td colspan="2">跨2列</td>
<td rowspan="2">跨2行</td>
<th> - 表格标题单元格定义表头单元格,默认加粗居中
<th>姓名</th>
<th scope="col">年龄</th> <!-- 列标题 -->
<th scope="row">总计</th> <!-- 行标题 -->
<thead> - 定义表格的页眉<tbody> - 定义表格的主体<tfoot> - 定义表格的页脚<colgroup>``col - 对表格中的列进行组合,以便对其进行格式化<table border="1">
<colgroup>
<col span="2" style="background-color:red">
<col style="background-color:yellow">
</colgroup>
<tr>
<th>ISBN</th>
<th>Title</th>
<th>Price</th>
</tr>
<tr>
<td>3476896</td>
<td>My first HTML</td>
<td>$53</td>
</tr>
</table>
<caption> - 定义表格的标题<table>
<caption>
侏罗纪时期的恐龙
</caption>
…
</table>
<table>
<caption>员工信息表</caption>
<thead> <!-- 表头 -->
<tr>
<th>ID</th>
<th>姓名</th>
<th>部门</th>
</tr>
</thead>
<tbody> <!-- 表体 -->
<tr>
<td>001</td>
<td>张三</td>
<td>技术部</td>
</tr>
<tr>
<td>002</td>
<td>李四</td>
<td>市场部</td>
</tr>
</tbody>
<tfoot> <!-- 表脚 -->
<tr>
<td colspan="2">总计</td>
<td>2人</td>
</tr>
</tfoot>
</table>
<table border="1">
<tr>
<td rowspan="2">跨2行</td>
<td>正常</td>
</tr>
<tr>
<!-- 上一行已占用,此行少一个单元格 -->
<td>正常</td>
</tr>
<tr>
<td colspan="2">跨2列</td>
</tr>
</table>
<table cellspacing="10" cellpadding="5" border="1">
<tr>
<td>单元格间距10px</td>
<td>内边距5px</td>
</tr>
</table>
<th> 元素的关联范围,帮助屏幕阅读器和辅助技术理解表格结构。<table border="1">
<caption>2024年部门业绩表</caption>
<thead>
<tr>
<th scope="col">部门</th>
<th scope="col">季度</th>
<th scope="col">销售额</th>
<th scope="col">增长率</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="rowgroup" rowspan="4">销售部</th>
<th scope="row">Q1</th>
<td>¥1,200,000</td>
<td>+15%</td>
</tr>
<tr>
<th scope="row">Q2</th>
<td>¥1,500,000</td>
<td>+25%</td>
</tr>
<tr>
<th scope="row">Q3</th>
<td>¥1,300,000</td>
<td>+8%</td>
</tr>
<tr>
<th scope="row">Q4</th>
<td>¥1,800,000</td>
<td>+30%</td>
</tr>
</tbody>
</table>
scope可选值:
scope="col" - 列标题scope="row" - 行标题scope="colgroup" - 列组标题scope="rowgroup" - 行组标题使用 CSS 替代传统属性