在談「表格邊框合併」之前,先看看預設狀態下,表格加上邊框究竟是什麼模樣。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
table,th,td{border:1px solid gray;}
</style>
</head>
<body>
<table>
<caption>表格標題</caption>
<!--表頭-->
<thead>
<tr>
<th>表頭單元格1</th>
<th>表頭單元格2</th>
</tr>
</thead>
<!--表身-->
<tbody>
<tr>
<td>標準單元格1</td>
<td>標準單元格2</td>
</tr>
<tr>
<td>標準單元格1</td>
<td>標準單元格2</td>
</tr>
</tbody>
<!--表腳-->
<tfoot>
<tr>
<td>標準單元格1</td>
<td>標準單元格2</td>
</tr>
</tfoot>
</table>
</body>
</html>
在瀏覽器中預覽,效果如下:
順帶一提,<thead>、<tbody> 和 <tfoot> 都是表格的語意化結構標籤,在 HTML 代碼語意化中佔有重要地位,細節可參考「表格語意化標籤」一節。
如圖所示,預設情況下單元格與單元格之間存在明顯空隙,相鄰的兩格會出現雙線。若想消除這段空隙,CSS 提供了 border-collapse 屬性。
語法:
border-collapse:屬性值;
說明:
border-collapse 是表格專屬屬性,在其他元素上寫了也不會有效果。
屬性取值如下:
| border-collapse 屬性值 | 說明 |
|---|---|
| separate | 預設值,邊框分開,不合併 |
| collapse | 邊框合併,若相鄰則共用同一個邊框 |
separate 意思是「分離」,而 collapse 意思是「折疊、瓦解」。
舉例:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>border-collapse屬性</title>
<style type="text/css">
table,th,td{border:1px solid gray;}
table{border-collapse:collapse;}
</style>
</head>
<body>
<table>
<caption>表格標題</caption>
<!--表頭-->
<thead>
<tr>
<th>表頭單元格1</th>
<th>表頭單元格2</th>
</tr>
</thead>
<!--表身-->
<tbody>
<tr>
<td>標準單元格1</td>
<td>標準單元格2</td>
</tr>
<tr>
<td>標準單元格1</td>
<td>標準單元格2</td>
</tr>
</tbody>
<!--表腳-->
<tfoot>
<tr>
<td>標準單元格1</td>
<td>標準單元格2</td>
</tr>
</tfoot>
</table>
</body>
</html>
在瀏覽器中預覽,效果如下:
分析:
相鄰單元格共用同一條邊框,雙線消失,整個表格看起來乾淨俐落。這也是製作數據表格時最常套用的設定。
記住:只要在 table 元素上設定 border-collapse 即可,不必在 th、td 上重複宣告,避免代碼冗餘。