HTML表格简介
HTML表格用于在网页上展示表格化的数据。表格由行和列组成,可以包含表头、数据和标题等元素。
基本表格结构
一个基本的HTML表格由以下标签构成:
- <table> - 定义表格
- <tr> - 定义表格行
- <td> - 定义表格单元格
- <th> - 定义表头单元格(通常加粗居中)
<table>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>城市</th>
</tr>
<tr>
<td>张三</td>
<td>25</td>
<td>北京</td>
</tr>
</table>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>城市</th>
</tr>
<tr>
<td>张三</td>
<td>25</td>
<td>北京</td>
</tr>
</table>
预览效果:
| 姓名 | 年龄 | 城市 |
|---|---|---|
| 张三 | 25 | 北京 |
表格高级功能
表格标题 <caption>
使用<caption>标签为表格添加标题:
<table>
<caption>员工信息表</caption>
<tr>
<th>姓名</th>
<th>职位</th>
</tr>
</table>
<caption>员工信息表</caption>
<tr>
<th>姓名</th>
<th>职位</th>
</tr>
</table>
合并单元格
使用colspan和rowspan属性合并单元格:
<table>
<tr>
<th colspan="2">个人信息</th>
</tr>
<tr>
<td rowspan="2">张三</td>
<td>25岁</td>
</tr>
<tr>
<td>北京</td>
</tr>
</table>
<tr>
<th colspan="2">个人信息</th>
</tr>
<tr>
<td rowspan="2">张三</td>
<td>25岁</td>
</tr>
<tr>
<td>北京</td>
</tr>
</table>
预览效果:
| 个人信息 | |
|---|---|
| 张三 | 25岁 |
| 北京 | |
表格结构标签
表格分区
为了更好地组织表格内容,可以使用以下标签:
- <thead> - 定义表格的页眉
- <tbody> - 定义表格的主体
- <tfoot> - 定义表格的页脚
<table>
<thead>
<tr>
<th>产品</th>
<th>价格</th>
</tr>
</thead>
<tbody>
<tr>
<td>笔记本电脑</td>
<td>¥5,999</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>总计</td>
<td>¥5,999</td>
</tr>
</tfoot>
</table>
<thead>
<tr>
<th>产品</th>
<th>价格</th>
</tr>
</thead>
<tbody>
<tr>
<td>笔记本电脑</td>
<td>¥5,999</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>总计</td>
<td>¥5,999</td>
</tr>
</tfoot>
</table>
预览效果:
| 产品 | 价格 |
|---|---|
| 笔记本电脑 | ¥5,999 |
| 鼠标 | ¥99 |
| 总计 | ¥6,098 |
注意: 使用表格结构标签可以提高表格的可访问性,并有助于CSS样式应用和JavaScript操作。
表格样式与属性
常用表格属性
HTML5中已不推荐使用表格属性进行样式设置(建议使用CSS),但了解这些属性仍有帮助:
- border - 设置表格边框宽度
- cellpadding - 设置单元格内边距
- cellspacing - 设置单元格间距
- width - 设置表格宽度
<table border="1" cellpadding="10" cellspacing="0" width="100%">
<!-- 表格内容 -->
</table>
<!-- 表格内容 -->
</table>
使用CSS美化表格
现代网页设计推荐使用CSS来美化表格:
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
th {
background-color: #4CAF50;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
</style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
padding: 12px;
text-align: left;
}
th {
background-color: #4CAF50;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
</style>
练习:创建课程表
尝试创建一个简单的课程表,包含以下要求:
- 表格标题为"我的课程表"
- 包含星期一到星期五的列
- 包含上午和下午的行
- 使用合并单元格表示连续课程
完成后,你的表格应该类似这样:
| 时间 | 星期一 | 星期二 | 星期三 | 星期四 | 星期五 |
|---|---|---|---|---|---|
| 上午 | 数学 | 英语 | 物理实验 | 化学 | 生物 |
| 下午 | 体育 | 历史 | 地理 | 美术 |