表格斜線表頭常用於同時標示「行標題」與「欄標題」(如課程對應教師、產品對應月份)。早期需用 JavaScript 計算座標繪製 1px 圖片,現代 CSS 與 SVG 提供更優雅、無腳本、可縮放的解決方案。本文詳細介紹兩種主流實作方式、程式碼範例與優缺點比較。
左上角儲存格需同時顯示「科目」與「學生」,斜線分隔雙向標題:
學生A 學生B 學生C
數學 55 66 77
英語 99 68 71
語文 33 44 55
利用 `border` 形成三角形,配合 `::before`/`::after` 偽元素定位文字,斜線由容器 `border-bottom` + `border-right` 組成。
<table class="diagonal-header">
<thead>
<tr>
<th class="corner">
<span class="row-header">科目</span>
<span class="col-header">學生</span>
</th>
<th>學生A</th>
<th>學生B</th>
<th>學生C</th>
</tr>
</thead>
<tbody>
<tr><th>數學</th><td>55</td><td>66</td><td>77</td></tr>
<tr><th>英語</th><td>99</td><td>68</td><td>71</td></tr>
<tr><th>語文</th><td>33</td><td>44</td><td>55</td></tr>
</tbody>
</table>
.diagonal-header {
border-collapse: collapse;
width: 100%;
max-width: 500px;
}
.diagonal-header th,
.diagonal-header td {
border: 1px solid #999;
padding: 12px;
text-align: center;
}
.diagonal-header thead th {
background: #f5f5f5;
font-weight: 600;
}
/* 關鍵:斜線儲存格 */
.diagonal-header .corner {
position: relative;
min-width: 100px;
height: 60px;
border-bottom: 2px solid #333; /* 斜線下邊 */
border-right: 2px solid #333; /* 斜線右邊 */
padding: 0;
}
/* 偽元素定位文字 */
.corner::before,
.corner::after {
content: attr(data-label);
position: absolute;
font-size: 0.85rem;
font-weight: 600;
color: #333;
white-space: nowrap;
}
.corner::before { /* 行標題:左下 */
content: attr(data-row);
bottom: 4px;
left: 4px;
transform: rotate(-45deg);
transform-origin: left bottom;
}
.corner::after { /* 欄標題:右上 */
content: attr(data-col);
top: 4px;
right: 4px;
transform: rotate(-45deg);
transform-origin: right top;
}
/* HTML 需改為 data 屬性 */
<th class="corner" data-row="科目" data-col="學生"></th>
<th class="corner-svg">
<svg viewBox="0 0 100 60" preserveAspectRatio="none">
<!-- 斜線:從左下 (0,60) 到右上 (100,0) -->
<line x1="0" y1="60" x2="100" y2="0" stroke="#333" stroke-width="2" />
<!-- 行標題:左下區域 -->
<text x="10" y="50" font-size="12" font-weight="600" fill="#333" text-anchor="start">科目</text>
<!-- 欄標題:右上區域 -->
<text x="90" y="15" font-size="12" font-weight="600" fill="#333" text-anchor="end">學生</text>
</svg>
</th>
.corner-svg {
width: 100px;
height: 60px;
padding: 0;
}
.corner-svg svg {
width: 100%;
height: 100%;
display: block;
}
| 比較項目 | CSS 邊框三角形 | SVG |
|---|---|---|
| 實作複雜度 | 低(純 CSS) | 中(需撰寫 SVG) |
| 文字旋轉清晰度 | 可能因瀏覽器渲染產生鋸齒 | 向量文字,任意縮放銳利 |
| 斜線角度彈性 | 固定 45°(可調但需重算定位) | 任意角度,修改座標即可 |
| 多行/長文字支援 | 困難,易溢出 | 原生支援 ` |
| 瀏覽器相容性 | IE9+、所有現代瀏覽器 | IE9+、所有現代瀏覽器 |
| 維護性 | 樣式分散在 CSS,修改需改多處 | 結構與樣式封裝在 SVG 內,較集中 |
簡單專案、固定 45° 斜線、文字較短 → 採用 CSS 邊框三角形,零依賴、極輕量。
複雜表頭、需任意角度、多語系、長文字、高精度列印 → 採用 SVG,一次解決縮放、清晰度與維護問題。兩種方案皆無需 JavaScript,符合漸進增強原則。