!文章内容如有错误或排版问题,请提交反馈,非常感谢!
HTML表格在展示结构化数据时非常有用。HTML表格是用于在网页中展示结构化数据的一种标记语言元素。表格由<table>元素定义,表格的行由<tr>元素定义,而单元格则由<td>元素(用于数据单元格)和<th>元素(用于表头单元格)定义。
HTML表格基础
HTML表格由多个标签组成,这些标签定义了表格的行和列结构。
表格基本示例
<table> <tr> <th>Header1</th> <th>Header2</th> <th>Header3</th> </tr> <tr> <td>Row1,Cell1</td> <td>Row1,Cell2</td> <td>Row1,Cell3</td> </tr> <tr> <td>Row2,Cell1</td> <td>Row2,Cell2</td> <td>Row2,Cell3</td> </tr> </table>
表格标签
- <table>:定义表格的开始和结束。
- <tr>:定义表格的一行。
- <th>:定义表格的表头单元格,通常呈现为粗体且居中。
- <td>:定义表格的标准单元格。
表格属性
- 全局属性
- id:表格的唯一标识符。
- class:表格的样式类。
- style:行内样式。
- 特殊属性
- border:设置表格边框的宽度。
- cellpadding和 cellspacing
- cellpadding:单元格内部的间距。
- cellspacing:单元格之间的间距。
- colspan和 rowspan
- colspan:合并列。
- rowspan:合并行。
表格样式
- 内联样式:通过style属性直接在HTML标签内定义样式。
- 内部样式表:使用<style>标签在HTML文档的<head>部分定义样式。
- 外部样式表:使用外部CSS文件定义样式。
表格嵌套
表格内部可以嵌套另一个表格。
<table border="1"> <tr> <th>Header1</th> <th>Header2</th> </tr> <tr> <td> <table border="1"> <tr> <td>NestedRow1,Cell1</td> <td>NestedRow1,Cell2</td> </tr> </table> </td> <td>Row2,Cell2</td> </tr> </table>
高级表格功能
表格标题和摘要
<caption>:为表格添加标题。
<table border="1"> <caption>TableCaption</caption> <tr> <th>Header1</th> <th>Header2</th> </tr> </table>
summary:为表格提供简要说明,通常用于无障碍访问。
<table border="1" summary="This table contains data about..."> <caption>TableCaption</caption> <tr> <th>Header1</th> <th>Header2</th> </tr> </table>
表格分组
<thead>、<tbody> 和 <tfoot>
- <thead>:表头部分。
- <tbody>:表体部分。
- <tfoot>:表尾部分。
<table border="1"> <thead> <tr> <th>Header1</th> <th>Header2</th> </tr> </thead> <tbody> <tr> <td>Row1,Cell1</td> <td>Row1,Cell2</td> </tr> <tr> <td>Row2,Cell1</td> <td>Row2,Cell2</td> </tr> </tbody> <tfoot> <tr> <td>Footer1</td> <td>Footer2</td> </tr> </tfoot> </table>
表格与JavaScript
动态生成表格:使用JavaScript动态创建表格。
动态修改表格:使用 JavaScript 修改表格内容。
Row 1, Cell 1 | Row 1, Cell 2 |
Row 2, Cell 1 | Row 2, Cell 2 |
实战项目
学生成绩表
创建一个显示学生成绩的表格,包含姓名、学科和成绩等字段,并添加一些基本样式。
Student Scores Student Scores
Name | Subject | Score |
---|---|---|
John Doe | Math | 95 |
Jane Smith | English | 88 |
Sam Brown | History | 92 |
可排序的表格
创建一个可排序的表格,用户点击表头时可以根据该列的内容排序。
Sortable Table Sortable Table
Name | Score |
---|---|
John Doe | 95 |
Jane Smith | 88 |
Sam Brown | 92 |
参考链接: