表格 <th><caption>
<caption> 是 HTML 表格里负责显示“表格的标题”元素,<th> 则是负责显示“某一栏或某一列的标题”元素,这篇教学会介绍 <th> 和 <caption> 的用法。
认识 <th> 和 <caption>
<caption> 是 HTML 表格里负责显示“表格的标题”元素,<th> 则是负责显示“某一栏或某一列的标题”元素,这两个元素并不是必要的元素,但使用后能替表格加入更多清楚的提示。
<th>和<caption>属于“容器元素”,需要有“起始标签”以及“结束标签”。<th>显示类型为“table-cell 表格水平栏元素”,只能作为<tr>的子元素。<aption>显示类型为“table-caption 表格垂直列元素”,只能作为<table>的子元素。
下方的 HTML 会在表格加入 <caption>,以及将第一列改成 <th> ( 额外加入边界值样式 )。
<style>
td{
padding:20px;
}
</style>
<table border=1>
<caption>我是表格</caption>
<tr>
<th>a</th>
<th>b</th>
<th>c</th>
</tr>
<tr>
<td>100</td>
<td>200</td>
<td>300</td>
</tr>
</table>
下方的 HTML 则是将每一列的第一栏都改成 <th>。
<style>
td{
padding:20px;
}
</style>
<table border=1>
<caption>我是表格</caption>
<tr>
<th>a</th>
<td>b</td>
<td>c</td>
</tr>
<tr>
<th>100</th>
<td>200</td>
<td>300</td>
</tr>
</table>
<th> 和 <caption> 支援属性
<th> 和 <caption> 支援“全域属性”以及“可见元素的事件属性”( 参考“HTML 元素属性”),例如下方的 HTML,会将 <th> 加入 style 属性,改变其背景颜色。
<style>
td{
padding:20px;
}
</style>
<table border=1>
<caption>我是表格</caption>
<tr>
<th style="background:#ccc;">a</th>
<th style="background:#ccc;">b</th>
<th style="background:#ccc;">c</th>
</tr>
<tr>
<td>100</td>
<td>200</td>
<td>300</td>
</tr>
</table>
<th> colspan、rowspan 属性
<th> 和 <td> 一样,除了共用的属性,还存在“合并列或栏”的 colspan 和 rowspan 属性,colspan 是用来水平合并多栏 ( column ) 的储存格,rowspan 则用来垂直合并多列 ( row ) 的储存格,以下方的 HTML 为例,第一个 <th> 里设定属性 colspan 为 2,表示第一个 <th> 水平合并了两个储存格 ( 注意第一个 <tr> 里的 <th> 只有两个 )。
<style>
td{
padding:20px;
}
</style>
<table border=1>
<caption>我是表格</caption>
<tr>
<th colspan=2>a</th>
<th>c</th>
</tr>
<tr>
<td>100</td>
<td>200</td>
<td>300</td>
</tr>
</table>
下方的 HTML 里,第一个 <th> 里设定属性 rowspan 为 2,表示第一个 <th> 垂直合并了两个储存格 ( 注意第二个 <tr> 里没有 <th> )。
<style>
td, th{
padding:20px;
}
</style>
<table border=1>
<caption>我是表格</caption>
<tr>
<th rowspan=2>a</th>
<td>b</td>
<td>c</td>
</tr>
<tr>
<td>200</td>
<td>300</td>
</tr>
</table>
<th> 和 <caption> 默认样式
下方是 <th> 和 <caption> 的默认样式:
详细样式教学可参考:CSS 教学、认识表格、表格默认样式
th {
display: table-cell;
vertical-align: inherit;
font-weight: bold;
text-align: center;
}
caption {
display: table-caption;
text-align: center;
}
微信扫码关注
抖音扫码关注