HTML 表格基础

HTML 表格基础

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

html 复制代码
<table>
  <tr>
    <th>姓名</th>
    <th>年龄</th>
  </tr>
  <tr>
    <td>张三</td>
    <td>25</td>
  </tr>
</table>

表格边框与样式

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

html 复制代码
<table border="1">
  <tr>
    <th>标题1</th>
    <th>标题2</th>
  </tr>
  <tr>
    <td>数据1</td>
    <td>数据2</td>
  </tr>
</table>

推荐使用 CSS 控制样式:

html 复制代码
<style>
  table, th, td {
    border: 1px solid black;
    border-collapse: collapse;
  }
</style>

合并单元格

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

html 复制代码
<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> 用于分组表格内容。

html 复制代码
<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 实现响应式表格。

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

表格高级功能

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

html 复制代码
<table>
  <tr>
    <th scope="col">月份</th>
    <th scope="col">收入</th>
  </tr>
  <tr>
    <th scope="row">一月</th>
    <td>5000</td>
  </tr>
</table>
相关推荐
炫饭第一名2 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫2 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊2 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter2 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折3 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_3 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
Angelial3 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
jiayu3 小时前
Angular学习笔记24:Angular 响应式表单 FormArray 与 FormGroup 相互嵌套
前端
jiayu3 小时前
Angular6学习笔记13:HTTP(3)
前端
小码哥_常3 小时前
Kotlin抽象类与接口:相爱相杀的编程“CP”
前端