HTML表格的入门实例教程

173 阅读2分钟

在网络的早期,表格是构建布局的一个非常重要的部分。

后来,它们被CSS及其布局功能所取代,今天我们有了CSS Flexbox和CSS Grid这样强大的工具来构建布局。现在,表格只是用来,你猜是什么,用来构建表格的!

table 标签

你可以使用table 标签定义一个表格。

在表内我们将定义数据。我们以行为单位进行推理,这意味着我们向表格中添加行(而不是列)。我们将在行内定义列。

行是用tr 标签添加的,这也是我们唯一可以添加到table 元素中的东西。

<table>
  <tr></tr>
  <tr></tr>
  <tr></tr>
</table>

这是一个有3行的表格。

第一行可以承担标题的作用。

列头

表头包含一个列的名称,通常是用粗体字。

想想看,一个Excel / Google Sheets文档。顶部的A-B-C-D... header。

Column headers

我们使用th 标签来定义页眉。

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

表的内容

表格的内容是用td 标签定义的,在其他tr 元素里面。

<table>
  <tr>
    <th>Column 1</th>
    <th>Column 2</th>
    <th>Column 3</th>
  </tr>
  <tr>
    <td>Row 1 Column 1</td>
    <td>Row 1 Column 2</td>
    <td>Row 1 Column 3</td>
  </tr>
  <tr>
    <td>Row 2 Column 1</td>
    <td>Row 2 Column 2</td>
    <td>Row 2 Column 3</td>
  </tr>
</table>

如果你不添加任何CSS样式,浏览器就是这样渲染的。

No styling

添加这个CSS。

th, td {
  padding: 10px;
  border: 1px solid #333;
}

使得这个表格看起来更像一个合适的表格。

A proper table

跨越列和行

一行可以决定跨越2个或多个列,使用colspan 属性。

<table>
  <tr>
    <th>Column 1</th>
    <th>Column 2</th>
    <th>Column 3</th>
  </tr>
  <tr>
    <td colspan="2">Row 1 Columns 1-2</td>
    <td>Row 1 Column 3</td>
  </tr>
  <tr>
    <td colspan="3">Row 2 Columns 1-3</td>
  </tr>
</table>

A colspan example

或者它可以跨越2个或更多的行,使用rowspan 属性。

<table>
  <tr>
    <th>Column 1</th>
    <th>Column 2</th>
    <th>Column 3</th>
  </tr>
  <tr>
    <td colspan="2" rowspan="2">Rows 1-2 Columns 1-2</td>
    <td>Row 1 Column 3</td>
  </tr>
  <tr>
    <td>Row 2 Column 3</td>
  </tr>
</table>

A rowspan example

行标题

之前我解释了如何在表格的第一个tr 标签内使用th 标签来设置列标题。

你可以添加一个th 标签,作为不是表格第一个trtr 内的第一个元素,以获得行标题。

<table>
  <tr>
    <th></th>
    <th>Column 2</th>
    <th>Column 3</th>
  </tr>
  <tr>
    <th>Row 1</th>
    <td>Col 2</td>
    <td>Col 3</td>
  </tr>
  <tr>
    <th>Row 2</th>
    <td>Col 2</td>
    <td>Col 3</td>
  </tr>
</table>

Row headings

更多的标签来组织表格

你可以在表格中再添加3个标签,让它更有条理。

这在使用大型表格时是最好的。也可以适当地定义一个页眉和页脚。

这些标签是

  • thead
  • tbody
  • tfoot

它们包裹着tr 标签,以明确定义表格的不同部分。下面是一个用法示例。

<table>
  <thead>
    <tr>
      <th></th>
      <th>Column 2</th>
      <th>Column 3</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>Row 1</th>
      <td>Col 2</td>
      <td>Col 3</td>
    </tr>
    <tr>
      <th>Row 2</th>
      <td>Col 2</td>
      <td>Col 3</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td></td>
      <td>Footer of Col 1</td>
      <td>Footer of Col 2</td>
    </tr>
  </tfoot>
</table>

thead and tfoot

表的标题

一个表格应该有一个caption 标签来描述其内容。该标签应紧接在开头的table 标签之后。

<table>
  <caption>Dogs age</caption>
  <tr>
    <th>Dog</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Roger</td>
    <td>7</td>
  </tr>
</table>