7.1 标签 <caption>
标签 <caption>, <thead>, <tbody> 和 <tfoot> 用来 提升 HTML 表格的结构化和语义化标记。它们有助于整理数据,让表格对用户和搜索引擎更加容易理解和可访问。
标签 <caption>
<caption> 标签用于为表格添加标题。它有助于描述表格的内容,让表格对用户更加直观,同时对搜索引擎更加友好。
语法:
HTML
<table>
<caption>表格标题</caption>
<!-- 表格内容 -->
</table>
示例:
HTML
<table>
<caption>表格标题</caption>
<tr>
<th>名字</th>
<th>分数</th>
</tr>
<tr>
<td>Ivan</td>
<td>90</td>
</tr>
<tr>
<td>Maria</td>
<td>85</td>
</tr>
</table>
7.2 标签 <thead>
<thead> 标签用于将表格的标题行分组。可以把它看作是表格标题和主要内容之间的逻辑分离。
语法:
HTML
<table>
<thead>
<tr>
<th>标题 1</th>
<th>标题 2</th>
</tr>
</thead>
<!-- 表格内容 -->
</table>
示例:
HTML
<table>
<thead>
<tr>
<th>名字</th>
<th>分数</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ivan</td>
<td>90</td>
</tr>
<tr>
<td>Maria</td>
<td>85</td>
</tr>
</tbody>
</table>
7.3 标签 <tbody>
<tbody> 标签用来分组表格的主要内容部分。它可以将主要内容和表头以及表尾分开。
语法:
HTML
<table>
<thead>
<tr>
<th>标题 1</th>
<th>标题 2</th>
</tr>
</thead>
<tbody>
<!-- 表格内容 -->
</tbody>
</table>
示例:
HTML
<table>
<thead>
<tr>
<th>名字</th>
<th>分数</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ivan</td>
<td>90</td>
</tr>
<tr>
<td>Maria</td>
<td>85</td>
</tr>
</tbody>
</table>
7.4 标签 <tfoot>
标签 <tfoot> 通常用于表格的底部行分组,通常放置一些汇总或总结信息。
语法:
HTML
<table>
<thead>
<tr>
<th>标题 1</th>
<th>标题 2</th>
</tr>
</thead>
<tbody>
<!-- 表格内容 -->
</tbody>
<tfoot>
<tr>
<td>汇总 1</td>
<td>汇总 2</td>
</tr>
</tfoot>
</table>
完整示例:
HTML
<table>
<thead>
<tr>
<th>名字</th>
<th>分数</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ivan</td>
<td>90</td>
</tr>
<tr>
<td>Maria</td>
<td>85</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>平均分</td>
<td>87.5</td>
</tr>
</tfoot>
</table>
其实记住这个结构很简单:
表格结构说明
<table>: 表格的外部容器<caption>: 表格标题,用于描述内容<thead>: 分组表头行<tbody>: 分组表格的主要内容<tfoot>: 分组表格底部行
知识巩固
我们来创建一个包含所有标签的表格并为其添加样式。
HTML
<table>
<caption>考试成绩</caption>
<thead>
<tr>
<th>名字</th>
<th>分数</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ivan</td>
<td>91</td>
</tr>
<tr>
<td>Maria</td>
<td>94</td>
</tr>
<tr>
<td>Nina</td>
<td>89</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>平均分</td >
<td>91.33</td>
</tr>
</tfoot>
</table>
CSS
table {
width: 100%;
border-collapse: collapse;
margin: 20px 0;
font-size: 18px;
text-align: left;
}
caption {
caption-side: top;
font-weight: bold;
font-size: 20px;
margin-bottom: 10px;
}
th, td {
padding: 12px 15px;
border: 1px solid #ddd;
}
thead th {
background-color: #f2f2f2;
}
tbody tr:nth-child(even) {
background-color: #f9f9f9;
}
tfoot td {
font-weight: bold;
background-color: #f2f2f2;
}
GO TO FULL VERSION