【基础学习-html】5.html表格

新建表格

创建table元素

1
<table></table>

创建一行

使用tr元素(table row)

1
2
3
<table>
<tr></tr>
</table>

单元格

使用td元素(table data)

1
2
3
4
5
6
7
<table>
<tr>
<td>Lily</td>
<td>15</td>
<td></td>
</tr>
</table>

表头

使用th元素(table head),会自动加粗居中

1
2
3
4
5
6
7
8
9
10
11
12
<table>
<tr>
<th>name</th>
<th>age</th>
<th>gender</th>
</tr>
<tr>
<td>Lily</td>
<td>15</td>
<td></td>
</tr>
</table>

标题

标题使用caption元素;

1
2
3
4
5
6
7
8
9
10
11
12
13
<table>
<caption>一年一班统计</caption>
<tr>
<th>name</th>
<th>age</th>
<th>gender</th>
</tr>
<tr>
<td>Lily</td>
<td>15</td>
<td></td>
</tr>
</table>

合并单元格

使用colspanrowspan属性,值是一个int类型

例如:合并第一列的两行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<table>
<caption>一年一班统计</caption>
<tr>
<th>class</th>
<th>name</th>
<th>age</th>
<th>gender</th>
</tr>
<tr>
<td rowspan="2">一年一班</td>
<td>Lily</td>
<td>15</td>
<td></td>
</tr>
<tr>
<td>Abby</td>
<td>16</td>
<td></td>
</tr>
</table>

设置某一列的样式

使用colgroup容器包裹col元素

一般单独修改某一列,会写出等于列数 col数量,在单独设置样式

修改全部列,可以只使用一个col 并设置 span=""对应列数属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<table>
<caption>一年一班统计</caption>
<colgroup>
<col>
<col>
<col style="background:blue">
<col>
</colgroup>
<tr>
<th>class</th>
<th>name</th>
<th>age</th>
<th>gender</th>
</tr>
<tr>
<td rowspan="2">一年一班</td>
<td>Lily</td>
<td>15</td>
<td></td>
</tr>
<tr>
<td>Abby</td>
<td>16</td>
<td></td>
</tr>
</table>

结构化表格

添加thead, tfoot, 和 tbody

  • thead 需要放在表格头部,但是如果使用了colgroup,需要放在colgroup下面
  • tfoot 需要放在底部
  • tbody 需要放在thead 和tfoot中间
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<table>
<caption>一年一班统计</caption>
<colgroup>
<col>
<col>
<col style="background:blue">
<col>
</colgroup>
<thead>
<tr>
<th>class</th>
<th>name</th>
<th>age</th>
<th>gender</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="2">一年一班</td>
<td>Lily</td>
<td>15</td>
<td></td>
</tr>
<tr>
<td>Abby</td>
<td>16</td>
<td></td>
</tr>
</tbody>
</table>

scope属性

可以将数据单元格与表头单元格联系起来,不会产生视觉效果,是给视力障碍的人事使用

  • col规定单元格是列的表头。
  • row规定单元格是行的表头。
  • colgroup规定单元格是列组的表头。
  • rowgroup规定单元格是行组的表头。