一、表格
在HTML语法中,表格主要通过< table >、< tr >和< td >3个标签构成。
表格标签为< table >,行的标签为< tr >,表项的标签为< td >。
1.表格语法格式
<table border="边框宽距" width="表格宽度" height="表格高度" bordercolor="边框颜色" align="页面对齐方式" bgcolor="背景颜色"> <caption align="表格中对齐方式">标题</caption> <tr> <th scope="col">表头</th> <th scope="col">表头</th> <th scope="col">表头</th> </tr> <tr> <th scope="row">表头</th> <td>表项</td> <td>表项</td> </tr> </table>
复制
< caption >标签必须紧随< table >标签之后,为每个标签指定唯一标题。
2.表格属性
border | 表格边框宽度 |
width | 表格宽度 |
heigh | 表格长度 |
align | 表格相对周边对齐方式 |
bordercolor | 边框颜色 |
bgcolor | 背景颜色 |
scope | 表示单元格是列(low)、行(row)的表头 |
3.例子
运行代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>表格</title> </head> <body> <table border="1" width="600" height="600" bordercolor="blue" align="center" bgcolor="#cccccc"> <caption align="center">成绩单</caption> <tr align="center"> <td></td> <th scope="col">教师人数</th> <th scope="col">学生人数</th> <th scope="col">总人数</th> </tr> <tr align="center"> <th scope="row">2021年</td> <td>40</td> <td>400</td> <td>440</td> </tr> <tr align="center"> <th scope="row">2022年</th> <td>100</td> <td>1500</td> <td>1600</td> </tr> <tr align="center"> <th scope="row">2023年</th> <td>100</td> <td>1500</td> <td>1600</td> </tr> <tr align="center"> <th scope="row">2024年</th> <td>200</td> <td>4000</td> <td>4200</td> </tr> </table> </body> </html>
复制
运行结果如下:
二、不规则表格
使用 colspan 和 rowspan 属性用于建立不规则表格
1.跨行
<table> <tr> <td rowspan="所跨的行数">单元格内容</td> </tr> </table>
复制
rowspan 指明该单元格应有多少行的跨度,在 th 和 tr 标签中使用。
2.跨列
<table> <tr> <td colspan="所跨的行数">单元格内容</td> </tr> </table>
复制
colspan 指明该单元格应有多少列的跨度,在 th 和 tr 标签中使用。
注:跨越的单元格占用了原来的单元格要删除掉
3.例子
运行代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>不规则表格</title> </head> <body> <table border="1" width="400" height="200"> <tr> <td></td> <th scope="col">教师人数</th> <th scope="col">学生人数</th> <th scope="col">总人数</th> </tr> <tr> <th scope="row">2021年</th> <td colspan="2"></td> <td rowspan="2"></td> </tr> <tr> <th scope="row">2022年</th> <td></td> <td></td> </tr> <tr> <th scope="row">2023年</th> <td colspan="2" rowspan="2"></td> <td></td> </tr> <tr> <th scope="row">2024年</th> <td></td> </tr> </table> </body> </html>
复制
运行结果如下: