HTML 表格定义

HTMLHTMLBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

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

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


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL html(("HTML")) -.-> html/BasicStructureGroup(["Basic Structure"]) html(("HTML")) -.-> html/LayoutandSectioningGroup(["Layout and Sectioning"]) html(("HTML")) -.-> html/TablesGroup(["Tables"]) html/BasicStructureGroup -.-> html/basic_elems("Basic Elements") html/LayoutandSectioningGroup -.-> html/layout("Layout Elements") html/LayoutandSectioningGroup -.-> html/doc_flow("Document Flow Understanding") html/TablesGroup -.-> html/tables("Table Structure") html/TablesGroup -.-> html/tbl_access("Table Accessibility") subgraph Lab Skills html/basic_elems -.-> lab-70852{{"HTML 表格定义"}} html/layout -.-> lab-70852{{"HTML 表格定义"}} html/doc_flow -.-> lab-70852{{"HTML 表格定义"}} html/tables -.-> lab-70852{{"HTML 表格定义"}} html/tbl_access -.-> lab-70852{{"HTML 表格定义"}} end

创建表格

让我们从创建一个名为 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> 等额外标签来进一步自定义。借助这些工具,你可以创建复杂且信息丰富的表格,以便在网页上展示数据。