HTML 表格定义

HTMLBeginner
立即练习

介绍

HTML 表格通常用于在网页上展示表格数据。在本实验中,你将学习如何使用 <table><tr><td><th> 标签创建基本的 HTML 表格。

注意:你可以在 index.html 中练习编码,并学习如何在 Visual Studio Code 中编写 HTML。请点击右下角的 'Go Live' 以在端口 8080 上运行 Web 服务。然后,你可以刷新 Web 8080 标签以预览网页。

这是一个实验(Guided Lab),提供逐步指导来帮助你学习和实践。请仔细按照说明完成每个步骤,获得实际操作经验。根据历史数据,这是一个 初级 级别的实验,完成率为 85%。获得了学习者 100% 的好评率。

创建表格

让我们从创建一个名为 index.html 的新 HTML 文件并设置基本结构开始。在 <body> 标签内,创建一个 <table> 元素。该元素将包含表格的所有行和列。

<!doctype html>
<html>
  <head>
    <title>HTML Table Tutorial</title>
  </head>
  <body>
    <table></table>
  </body>
</html>

定义行

接下来,使用 <tr> 标签定义表格的行。每一行将包含一个或多个单元格。要创建单个单元格,请使用 <td> 标签。

<!doctype html>
<html>
  <head>
    <title>HTML Table Tutorial</title>
  </head>
  <body>
    <table>
      <tr>
        <td>Row 1 Cell 1</td>
        <td>Row 1 Cell 2</td>
      </tr>
      <tr>
        <td>Row 2 Cell 1</td>
        <td>Row 2 Cell 2</td>
      </tr>
    </table>
  </body>
</html>

添加表头

在某些情况下,你可能希望为表格添加一个表头行。为此,请使用 <th> 标签代替 <td> 标签。

<!doctype html>
<html>
  <head>
    <title>HTML Table Tutorial</title>
  </head>
  <body>
    <table>
      <tr>
        <th>Header 1</th>
        <th>Header 2</th>
      </tr>
      <tr>
        <td>Row 1 Cell 1</td>
        <td>Row 1 Cell 2</td>
      </tr>
      <tr>
        <td>Row 2 Cell 1</td>
        <td>Row 2 Cell 2</td>
      </tr>
    </table>
  </body>
</html>

添加边框和样式

默认情况下,HTML 表格的样式非常简单,且没有边框。要为表格添加边框,可以使用 CSS 的 border 属性。

<!doctype html>
<html>
  <head>
    <title>HTML Table Tutorial</title>
    <style>
      table,
      th,
      td {
        border: 1px solid black;
        border-collapse: collapse;
      }
      th,
      td {
        padding: 10px;
        text-align: center;
      }
    </style>
  </head>
  <body>
    <table>
      <tr>
        <th>Header 1</th>
        <th>Header 2</th>
      </tr>
      <tr>
        <td>Row 1 Cell 1</td>
        <td>Row 1 Cell 2</td>
      </tr>
      <tr>
        <td>Row 2 Cell 1</td>
        <td>Row 2 Cell 2</td>
      </tr>
    </table>
  </body>
</html>

总结

通过本教程,你已经学会了如何创建一个基本的 HTML 表格并使用 CSS 对其进行样式设置。表格可以通过为单元格添加 colspanrowspan 等属性,以及使用 <caption><thead> 等额外标签来进一步自定义。借助这些工具,你可以创建复杂且信息丰富的表格,以便在网页上展示数据。