HTML5表格语法格式详解

HTML5 表格的基本结构

HTML5 表格由 <table> 标签定义,表格中的每一行由 <tr> 标签定义,表头单元格由 <th> 标签定义,数据单元格由 <td> 标签定义。表格的基本结构如下:

html 复制代码
<table>
  <tr>
    <th>表头1</th>
    <th>表头2</th>
  </tr>
  <tr>
    <td>数据1</td>
    <td>数据2</td>
  </tr>
</table>

表格的标题

可以使用 <caption> 标签为表格添加标题,标题通常显示在表格的上方。

html 复制代码
<table>
  <caption>表格标题</caption>
  <tr>
    <th>表头1</th>
    <th>表头2</th>
  </tr>
  <tr>
    <td>数据1</td>
    <td>数据2</td>
  </tr>
</table>

表格的表头和表体

可以使用 <thead><tbody><tfoot> 标签分别定义表格的表头、表体和表脚部分。

html 复制代码
<table>
  <thead>
    <tr>
      <th>表头1</th>
      <th>表头2</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>数据1</td>
      <td>数据2</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>表脚1</td>
      <td>表脚2</td>
    </tr>
  </tfoot>
</table>

合并单元格

可以通过 colspanrowspan 属性合并单元格。colspan 用于合并列,rowspan 用于合并行。

html 复制代码
<table>
  <tr>
    <th colspan="2">合并的表头</th>
  </tr>
  <tr>
    <td rowspan="2">合并的行</td>
    <td>数据1</td>
  </tr>
  <tr>
    <td>数据2</td>
  </tr>
</table>

表格的样式和边框

可以通过 CSS 为表格添加样式和边框。使用 border 属性可以设置表格边框,但推荐使用 CSS 进行样式控制。

html 复制代码
<style>
  table {
    border-collapse: collapse;
    width: 100%;
  }
  th, td {
    border: 1px solid black;
    padding: 8px;
    text-align: left;
  }
</style>
<table>
  <tr>
    <th>表头1</th>
    <th>表头2</th>
  </tr>
  <tr>
    <td>数据1</td>
    <td>数据2</td>
  </tr>
</table>

表格的响应式设计

为了使表格在移动设备上具有良好的显示效果,可以使用 overflow-x: auto; 来添加水平滚动条。

html 复制代码
<div style="overflow-x: auto;">
  <table>
    <tr>
      <th>表头1</th>
      <th>表头2</th>
      <th>表头3</th>
      <th>表头4</th>
    </tr>
    <tr>
      <td>数据1</td>
      <td>数据2</td>
      <td>数据3</td>
      <td>数据4</td>
    </tr>
  </table>
</div>
相关推荐
anOnion4 小时前
构建无障碍组件之Menu Button pattern
前端·html·交互设计
用户47949283569155 小时前
claude Fable用不了?把Gpt 5.5pro接到你的claude code里
前端·后端
zhangxingchao7 小时前
Kotlin常用的Flow 操作符整理
前端
IT_陈寒9 小时前
React的useState居然还有这种坑?我差点删库跑路
前端·人工智能·后端
Pedantic10 小时前
SwiftUI 手势笔记
前端·后端
橙子家10 小时前
浏览器缓存之【结构化数据库与缓存】: IndexedDB、Cache storage 和 Storage buckets
前端
user205855615181310 小时前
X6 中边悬浮置顶,规避 `mouseleave` 事件丢失问题
前端
李明卫杭州10 小时前
CSS aspect-ratio 属性完全指南
前端
Pedantic12 小时前
SwiftUI 手势层级(Gesture Hierarchy)详解
前端