HTML 表格
2025-04-24
18
参考资料
HTML 表格格式化
基本介绍
HTML表格用于在网页上展示行列数据,由<table>
标签定义,包含行(<tr>
)、表头单元格(<th>
)和数据单元格(<td>
)。
主要标签
<table>
- 定义表格<tr>
- 定义表格行<th>
- 定义表头单元格<td>
- 定义标准单元格<caption>
- 定义表格标题<thead>
- 定义表头区域<tbody>
- 定义表格主体<tfoot>
- 定义表格页脚
基本用法
<table> <caption>学生成绩表</caption> <thead> <tr> <th>姓名</th> <th>数学</th> <th>语文</th> </tr> </thead> <tbody> <tr> <td>张三</td> <td>90</td> <td>85</td> </tr> <tr> <td>李四</td> <td>78</td> <td>92</td> </tr> </tbody> <tfoot> <tr> <td>平均分</td> <td>84</td> <td>88.5</td> </tr> </tfoot> </table>
常用属性
border
- 设置表格边框宽度cellpadding
- 设置单元格内边距cellspacing
- 设置单元格间距colspan
- 单元格横跨列数rowspan
- 单元格纵跨行数
CSS扩展样式
/* 基本表格样式 */ table { width: 100%; border-collapse: collapse; /* 合并边框 */ margin: 20px 0; } /* 单元格样式 */ th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } /* 表头样式 */ th { background-color: #f2f2f2; font-weight: bold; } /* 斑马条纹效果 */ tr:nth-child(even) { background-color: #f9f9f9; } /* 悬停效果 */ tr:hover { background-color: #f1f1f1; } /* 响应式表格 */ @media screen and (max-width: 600px) { table { border: 0; } table thead { display: none; } table tr { margin-bottom: 10px; display: block; border: 1px solid #ddd; } table td { display: block; text-align: right; border-bottom: 1px solid #ddd; } table td:before { content: attr(data-label); float: left; font-weight: bold; } }
高级功能实例
合并单元格
<table border="1"> <tr> <th rowspan="2">姓名</th> <th colspan="2">成绩</th> </tr> <tr> <th>数学</th> <th>语文</th> </tr> <tr> <td>张三</td> <td>90</td> <td>85</td> </tr> </table>
固定表头滚动表格
.table-container { height: 300px; overflow: auto; } table thead th { position: sticky; top: 0; background: #f2f2f2; }
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。