在了解什麼叫“表格邊框合並”之前,我們先來看一下在默認情況下表格加入邊框是怎樣的一個效果。
在線測試
<!DOCTYPE html>
<html xmlns="http://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意思是“折疊,瓦解”。
舉例:
在線測試
<!DOCTYPE html>
<html xmlns="http://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這些元素也設置,造成代碼冗余。