HTML的`<table>`元素表示表格数据

常用标签

最简单的方法:<tr><td>

<tr>表示一行的开始,<td>表示每个表格数据

1
2
3
4
5
6
7
8
9
10
<table>
<tr>
<td>item1</td>
<td>item2</td>
</tr>
<tr>
<td>item3</td>
<td>item4</td>
</tr>
</table>

表头:<th>

表格的表头使用<th>标签进行定义

1
2
3
4
5
6
7
8
9
10
<table>
<tr>
<th>head1</th>
<th>head2</th>
</tr>
<tr>
<td>item1</td>
<td>item2</td>
</tr>
</table>

也可以定义横向的表格

1
2
3
4
5
6
7
8
9
10
<table>
<tr>
<th>head1</th>
<td>item1</td>
</tr>
<tr>
<th>head2</th>
<td>item2</td>
</tr>
</table>

更加语义化的标签:<thead><tbody><tfoot>

<thead>标签定义了一组由表格的列表头组成的行

<tbody>标签主要包含了表格的主体部分

<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
<table>
<thead>
<tr>
<th>Items</th>
<th>Expenditure</th>
</tr>
</thead>
<tbody>
<tr>
<th>Donuts</th>
<td>3,000</td>
</tr>
<tr>
<th>Stationary</th>
<td>18,000</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Totals</th>
<td>21,000</td>
</tr>
</tfoot>
</table>

不论thead、tbody和tfoot在文档中出现的顺序是怎样的,浏览器都会按照thead、tbody和tfoot的顺序渲染

其他标签

  • <caption>表示表格的题目

  • <col>标签用于定义表格中的列,并用于定义所有公共单元格上的公共语义。它通常位于<colgroup>标签内

    1
    2
    3
    4
    <colgroup>
    <col span="2" class="col1">
    <col span="2" class="col2">
    </colgroup>
  • 若想生成跨行或者跨列的单元格,可以使用rowspan或者colspan

    1
    <td rowspan="2">lalala</td>