精美的表格是前端開發中的常見需求。以往我們常寫大量頁面內聯 style 來堆砌樣式,導致可讀性和可維護性都很差。這裡推薦直接透過一個 table.css 來生成細線表格。
第一步:引入樣式文件。
<link rel="stylesheet" type="text/css" href="./css/table.css"/>
第二步:為表格套用 class 即可。
<table class="table">
你只需給 table 加上 class="table",無需對任何 tr、td 做額外操作。若想靈活控制寬度,可寫成 <table class="table" style="width:600px">;若想讓某些 td 有背景色,只需給該 td 加上 class="color" 即可。
/*表格樣式。*/
.table {
width:100%;
padding: 0px;
margin: 0px;
font-family:Arial, Tahoma, Verdana, Sans-Serif,宋體;
border-left:1px solid #ADD8E6;
border-collapse:collapse;
}
/*表頭樣式。*/
.table th {
font-size:12px;
font-weight:600;
color: #303030;
border-right: 1px solid #ADD8E6;
border-bottom: 1px solid #ADD8E6;
border-top: 1px solid #ADD8E6;
letter-spacing: 2px;
text-align: center;
padding: 10px 0px 10px 0px;
background: url(../images/tablehdbg.png);
white-space:nowrap;
overflow: hidden;
}
/*單元格樣式。*/
.table td {
border-right: 1px solid #ADD8E6;
border-bottom: 1px solid #ADD8E6;
background: #fff;
font-size:12px;
padding: 3px 3px 3px 6px;
color: #303030;
word-break:break-all;
word-wrap:break-word;
white-space:normal;
}
/*藍色單元格樣式,主要用於隔行變色。*/
.table td.color{ background:#edf7f9; }
/*表格中超級鏈接樣式。*/
.table td a:link{ font-weight:400; color:#2259D7; text-decoration:none; }
.table td a:visited{ font-weight:400; color:#2259D7; text-decoration:none; }
.table td a:hover{ font-weight:400; text-decoration:underline; color:#303030; }
.table td a:active{ font-weight:400; text-decoration:none; color:#2259D7; }
關鍵在於 border-collapse:collapse 讓相鄰邊框合併為單線,配合淡藍色 #ADD8E6 呈現清爽的細線外觀。日後若想微調樣式或更換邊框顏色,只需在 table.css 中把色值 #ADD8E6 替換即可,完全不必改動 HTML 結構。