HTML 表格基础

发布于:2025-09-08 ⋅ 阅读:(24) ⋅ 点赞:(0)

HTML 表格基础

HTML 表格用于在网页上展示结构化数据。表格由 <table> 标签定义,包含行(<tr>)、表头单元格(<th>)和数据单元格(<td>)。

<table>
  <tr>
    <th>姓名</th>
    <th>年龄</th>
  </tr>
  <tr>
    <td>张三</td>
    <td>25</td>
  </tr>
</table>

表格边框与样式

默认情况下,HTML 表格无边框。可以通过 CSS 或 border 属性添加边框。

<table border="1">
  <tr>
    <th>标题1</th>
    <th>标题2</th>
  </tr>
  <tr>
    <td>数据1</td>
    <td>数据2</td>
  </tr>
</table>

推荐使用 CSS 控制样式:

<style>
  table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
  }
</style>

合并单元格

使用 colspanrowspan 属性可以合并单元格。

<table border="1">
  <tr>
    <th colspan="2">姓名与年龄</th>
  </tr>
  <tr>
    <td rowspan="2">张三</td>
    <td>25</td>
  </tr>
  <tr>
    <td>26</td>
  </tr>
</table>

表格标题与结构

<caption> 标签为表格添加标题,<thead><tbody><tfoot> 用于分组表格内容。

<table>
  <caption>学生信息</caption>
  <thead>
    <tr>
      <th>姓名</th>
      <th>分数</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>李四</td>
      <td>90</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>平均分</td>
      <td>85</td>
    </tr>
  </tfoot>
</table>

响应式表格

对于小屏幕设备,可以通过 CSS 或 JavaScript 实现响应式表格。

@media screen and (max-width: 600px) {
  table {
    display: block;
    overflow-x: auto;
  }
}

表格高级功能

HTML5 支持 scope 属性定义表头的作用范围,辅助屏幕阅读器。

<table>
  <tr>
    <th scope="col">月份</th>
    <th scope="col">收入</th>
  </tr>
  <tr>
    <th scope="row">一月</th>
    <td>5000</td>
  </tr>
</table>


网站公告

今日签到

点亮在社区的每一天
去签到