在 HTML 裡寫 border="1",看起來是一像素的框線,實際渲染出來的邊框卻是 2px。若真的需要一條 1px 的細線表格,該怎麼辦?
早期的解法有點繞:先給 table 一個背景色,再讓每個 td 使用另一種背景色,最後把 cellspacing 設為 1px。表格底色會從格子之間那一像素的縫隙透出來,視覺上就變成一條細框線。
<table align="center" bgcolor="#f90" border="0" cellpadding="0" cellspacing="1" width="80%"> <tr> <td bgcolor="#ffc"></td> <td bgcolor="#ffc"></td> <td bgcolor="#ffc"></td> </tr> <tr> <td bgcolor="#ffc"></td> <td bgcolor="#ffc"></td> <td bgcolor="#ffc"></td> </tr> <tr> <td bgcolor="#ffc"></td> <td bgcolor="#ffc"></td> <td bgcolor="#ffc"></td> </tr> </table>
這方法確實有效,但缺點很明顯:標籤屬性一堆,程式碼膨脹,而且想針對某個局部單獨調整線色或線寬時,會變得很難收拾。
CSS 提供了更乾淨的答案。只要讓相鄰儲存格的邊框合併,再直接替 td 指定 1px 實線邊框即可。
CSS 部分:
<style type="text/css">
<!--
table{
border-collapse: collapse;
}
td{
background: #ffc;
border: solid 1px #f90;
height: 22px;
}
-->
</style>
HTML 部分:
<table width="80%" align="center"> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> </table>
border-collapse: collapse 的重點在於相鄰儲存格共用同一條邊框,因此不會出現兩條 1px 疊成 2px 的情形,這正是 border="1" 視覺偏粗的根源。改用 CSS 之後,HTML 結構回歸純粹的資料表格,樣式全部集中在樣式表裡,要改線色、線寬、格子高度只需動一個地方;表格外框、內框、單側邊框也能各自獨立控制,彈性遠勝背景色硬擠的老技巧。