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>
相关推荐
灵感__idea1 天前
Hello 算法:贪心的世界
前端·javascript·算法
GreenTea1 天前
一文搞懂Harness Engineering与Meta-Harness
前端·人工智能·后端
killerbasd1 天前
牧苏苏传 我不装了 4/7
前端·javascript·vue.js
吴声子夜歌1 天前
ES6——二进制数组详解
前端·ecmascript·es6
码事漫谈1 天前
手把手带你部署本地模型,让你Token自由(小白专属)
前端·后端
ZC跨境爬虫1 天前
【爬虫实战对比】Requests vs Scrapy 笔趣阁小说爬虫,从单线程到高效并发的全方位升级
前端·爬虫·scrapy·html
爱上好庆祝1 天前
svg图片
前端·css·学习·html·css3
王夏奇1 天前
python中的__all__ 具体用法
java·前端·python
大家的林语冰1 天前
《前端周刊》尤大开源 Vite+ 全家桶,前端工业革命启动;尤大爆料 Void 云服务新产品,Vite 进军全栈开发;ECMA 源码映射规范......
前端·javascript·vue.js
jiayong231 天前
第 8 课:开始引入组合式函数
前端·javascript·学习