初面网初面网

表格(table)

用于展示结构化数据

每个表格均有若干行(由 <tr> 标签定义),每行被分割为若干单元格(由 <td> 标签定义),表格可以包含标题行(<th>)用于定义列的标题

  • tr,是table row的缩写,表示表格的一行
  • td,是table data的缩写,表示表格的一个单元格
  • th,是table header的缩写,表示表格的标题单元格

数据单元格可以包含文本、图片、列表、段落、表单、水平线、表格等等

一个简单的表格示例:

<table>
  <thead>
    <tr>
      <th>姓名</th>
      <th>年龄</th>
      <th>性别</th>
    </tr>
  </thead>
  <tbody>
  <tr>
    <td>张三</td>
    <td>25</td>
    <td>男</td>
  </tr>
  <tr>
    <td>李四</td>
    <td>30</td>
    <td>女</td>
  </tr>
  </tbody>
</table>

还可以是垂直标题

<table border="1">
  <tr>
    <th>姓名:</th>
    <td>小明</td>
  </tr>
  <tr>
    <th>年龄:</th>
    <td>25</td>
  </tr>
  <tr>
    <th>性别:</th>
    <td>男</td>
  </tr>
</table>

表格标题

表格标题用于描述表格的内容,通常放在表格的顶部

可以使用 <caption> 标签为表格添加标题,<caption> 标签必须放在 <table> 标签内部,且只能有一个 <caption> 标签

<table>
  <caption>人员信息</caption>
  <thead>
    <tr>
      <th>姓名</th>
      <th>年龄</th>
      <th>性别</th>
    </tr>
  </thead>
  <tbody>
  <tr>
    <td>张三</td>
    <td>25</td>
    <td>男</td>
  </tr>
  </tbody>
</table>

表格合并单元格

colspan 合并列单元格, rowspan 合并行单元格

<table border="1">
  <tr>
    <th>月份</th>
    <th colspan="2">销售数据</th>
    <th rowspan="2">总计</th>
  </tr>
  <tr>
    <th>产品A</th>
    <th>产品B</th>
  </tr>
  <tr>
    <td>一月</td>
    <td>100</td>
    <td>200</td>
    <td rowspan="2">600</td>
  </tr>
  <tr>
    <td>二月</td>
    <td>150</td>
    <td>250</td>
  </tr>
  <tr>
    <td colspan="3">季度总计</td>
    <td>600</td>
  </tr>
</table>

单元格边距和间距

边距,指的是内容和单元格边框之间的空间。使用 cellpadding 属性设置 间距,指的是单元格之间的空间。使用 cellspacing 属性设置

<table border="1" cellspacing="0" cellpadding="10">
  <tr>
    <th>姓名</th>
    <th>年龄</th>
    <th>性别</th>
  </tr>
  <tr>
    <td>张三</td>
    <td>25</td>
    <td>男</td>
  </tr>
</table>

表格列组与列属性

可以使用 <colgroup> 标签定义表格的列组,<colgroup> 标签必须放在 <table> 标签内部,且只能有一个 <colgroup> 标签

可以使用 <col> 标签定义表格的列,<col> 标签必须放在 <colgroup> 标签内部。使用 <col> 标签的 span 属性设置列跨越多列,默认值为 1

<table border="1">
  <colgroup>
    <col span="2" style="background-color:red">
    <col style="background-color:yellow">
  </colgroup>
  <tr>
    <th>书籍编号</th>
    <th>书名</th>
    <th>价格</th>
  </tr>
  <tr>
    <td>3476896</td>
    <td>HTML入门指南</td>
    <td>¥53</td>
  </tr>
</table>

表格的页眉、主题、页脚

  • <thead> 标签定义表格的页眉
  • <tbody> 标签定义表格的主题
  • <tfoot> 标签定义表格的页脚

这三个标签都必须放在 <table> 标签内部,且只能有一个

更新于 2025/12/14