Post

HTML表格

HTML表格

HTML表格标签

HTML表格由 <table> 标签定义,表格的行由 <tr> 标签定义,表格的头由 <th> 标签定义,表格的数据单元由 <td> 标签定义。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<table>
    <tr>
        <!-- &nbsp;表示空格 -->
        <th>&nbsp;</th>
        <th>表头1</th>
        <th>表头2</th>
        <th>表头3</th>
    </tr>
    <tr>
        <td>数据1</td>
        <td>数据2</td>
        <td>数据3</td>
    </tr>
</table>

允许单元格跨越多行和列

colspan 属性允许单元格跨越多列,rowspan 属性允许单元格跨越多行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<table border="1">
    <tr>
        <th>&nbsp;</th>
        <th>表头1</th>
        <th>表头2</th>
        <th>表头3</th>
    </tr>
    <tr>
        <td rowspan="2">数据1</td>
        <td>数据2</td>
        <td>数据3</td>
    </tr>
    <tr>
        <td colspan="2">数据4</td>
    </tr>
</table>

为同一列提供相同的样式

使用<col><colgroup>标签为同一列提供相同的样式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<table>
  <colgroup>
    <col />
    <col style="background-color: yellow" />
  </colgroup>
  <tr>
    <th>数据 1</th>
    <th>数据 2</th>
  </tr>
  <tr>
    <td>加尔各答</td>
    <td>橙汁</td>
  </tr>
  <tr>
    <td>机器人</td>
    <td>爵士乐</td>
  </tr>
</table>

表格标题

<caption>标签可以为表格增加一个标题,标题就放在 <table> 标签的下面。

1
2
3
4
5
6
7
<table>
  <caption>
    侏罗纪时期的恐龙
  </caption></table>

添加表格结构

<thead> 元素必须包住表格的表头部分。一般是第一行,往往都是每列的标题,但是不是每种情况都是这样的。如果你使用了 <col>/<colgroup> 元素,那么<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
25
26
27
28
29
30
31
32
<table>
    <caption>侏罗纪时期的恐龙</caption>
    
    <colgroup>
        <col />
        <col style="background-color: yellow" />
    </colgroup>
    
    <thead>
        <tr>
        <th>名称</th>
        <th>食物</th>
        </tr>
    </thead>
    
    <tbody>
        <tr>
        <td>加尔各答</td>
        <td>橙汁</td>
        </tr>
        <tr>
        <td>机器人</td>
        <td>爵士乐</td>
        </tr>
    </tbody>
    
    <tfoot>
        <tr>
        <td colspan="2">表格的总结信息</td>
        </tr>
    </tfoot>
</table>

参考

HTML 表格基础

HTML 表格进阶特性和无障碍

This post is licensed under CC BY 4.0 by the author.