本節將為大家講解 HTML 如何實現下圖所示表格效果,先來看看最終實現效果吧!
table.png
- 新建 table.html 文件,并輸入以下框架代碼(本文編輯器采用Notepad++);
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
</body>
</html>
- 對題目要求表格進行分析,可以發現該表格包含:表格標題,表頭和內容三部分,且表格共有五行。首先我們先創建表格標題,caption 標簽指定表格標題,代碼如下所示:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
<table border="1">
<caption>購物車</caption>
</table>
</body>
</html>
- 其次,創建五行內容,其中兩行為表頭,三行為內容。行用 <tr> 標簽表示,代碼如下所示:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
<table border="1">
<caption>購物車</caption>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
</body>
</html>
- 其次,構建表頭。表頭包含兩行,“名稱”和“小計”均占用兩行一列行,“2016-11-22”占用一行兩列,“重量”和“單價”均占用一行一列。rowspan 屬性指定單元格占用行數,colspan 屬性指定單元格占用列數,因此表頭構建代碼如下所示:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
<table border="1">
<caption>購物車</caption>
<tr>
<th rowspan="2">名稱</th>
<th colspan="2">2016-11-22</th>
<th rowspan="2">小計</th>
</tr>
<tr>
<th>重量</th>
<th>單價</th>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
</tr>
</table>
</body>
</html>
- 接下來,填充表格第3~4行內容,代碼如下所示:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
<table border="1">
<caption>購物車</caption>
<tr>
<th rowspan="2">名稱</th>
<th colspan="2">2016-11-22</th>
<th rowspan="2">小計</th>
</tr>
<tr>
<th>重量</th>
<th>單價</th>
</tr>
<tr>
<td>蘋果</td>
<td>3公斤</td>
<td>5元/公斤</td>
<td>15元</td>
</tr>
<tr>
<td>香蕉</td>
<td>2公斤</td>
<td>6元/公斤</td>
<td>12元</td>
</tr>
<tr>
</tr>
</table>
</body>
</html>
- 最后,填充表格第5行內容,其中“總價”占用一行三列,且居中顯示。屬性
colspan="3"
實現單元格占用三列效果,屬性align="center"
實現居中顯示效果,因此表格最終代碼實現如下所示:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
</head>
<body>
<table border="1">
<caption>購物車</caption>
<tr>
<th rowspan="2">名稱</th>
<th colspan="2">2016-11-22</th>
<th rowspan="2">小計</th>
</tr>
<tr>
<th>重量</th>
<th>單價</th>
</tr>
<tr>
<td>蘋果</td>
<td>3公斤</td>
<td>5元/公斤</td>
<td>15元</td>
</tr>
<tr>
<td>香蕉</td>
<td>2公斤</td>
<td>6元/公斤</td>
<td>12元</td>
</tr>
<tr>
<td colspan="3" align="center">總價</td>
<td>27元</td>
</tr>
</table>
</body>
</html>
相關資料:
W3School上的HTML教程:http://www.w3school.com.cn/tags/tag_table.asp
源碼 Github 鏈接:https://github.com/anyangxaut/HTML-Learning-Demo