表格左上角斜線分隔「分類/項目」是經典需求。傳統用 Word/Excel 畫斜線,網頁則用 CSS 邊框三角形、線性漸層或 SVG 實現。本文提供三種純 CSS 做法、語意化標記與響應式處理。
<table class="diagonal-header">
<thead>
<tr>
<th class="diagonal-cell" scope="col">
<span class="diagonal-label row-header">分類</span>
<span class="diagonal-label col-header">項目</span>
</th>
<th scope="col">1 月</th>
<th scope="col">2 月</th>
<th scope="col">3 月</th>
</tr>
</thead>
<tbody>...</tbody>
</table>
關鍵:scope="col"、雙 <span> 分別承載列標題與欄標題,螢幕閱讀器可正確朗讀。
.diagonal-header .diagonal-cell {
position: relative;
padding: 0; /* 由偽元素撐開 */
min-width: 100px;
height: 60px;
border-right: 1px solid #ddd;
border-bottom: 1px solid #ddd;
}
.diagonal-cell::before {
content: "";
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
border-bottom: 60px solid transparent;
border-right: 100px solid #eee; /* 斜線顏色 */
z-index: -1;
pointer-events: none;
}
/* 文字定位 */
.diagonal-label {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.8rem;
font-weight: 600;
color: #333;
}
.row-header { bottom: 8px; left: 8px; } /* 左下:分類 */
.col-header { top: 8px; right: 8px; } /* 右上:項目 */
原理:利用 border-bottom + border-right 形成直角三角形,透明邊框構成斜線。
.diagonal-header .diagonal-cell {
position: relative;
min-width: 100px; height: 60px;
background: linear-gradient(
to bottom right,
#fff 0%, #fff 49.5%,
#ddd 49.5%, #ddd 50.5%, /* 斜線 1px */
#eee 50.5%, #eee 100%
);
background-size: 100% 100%;
}
.diagonal-label { /* 同做法一 */ }
優點:單一背景層、無偽元素、易於調整斜線粗細/顏色/角度。
缺點:漸層銳利度受裝置像素比影響,極窄儲存格可能模糊。
<th class="diagonal-cell" scope="col">
<svg class="diagonal-svg" viewBox="0 0 100 60" preserveAspectRatio="none">
<line x1="0" y1="60" x2="100" y2="0" stroke="#ddd" stroke-width="1.5" />
</svg>
<span class="diagonal-label row-header">分類</span>
<span class="diagonal-label col-header">項目</span>
</th>
<style>
.diagonal-cell { position:relative; min-width:100px; height:60px; }
.diagonal-svg { position:absolute; inset:0; width:100%; height:100%; pointer-events:none; }
.diagonal-label { /* 同前 */ }
</style>
優點:向量不失真、可加動畫(stroke-dasharray)、支援任意角度曲線。
@media (max-width: 600px) {
.diagonal-cell { min-width: 80px; height: 50px; }
.diagonal-label { font-size: 0.7rem; }
/* 邊框三角形法需同步調整 border 寬度 */
.diagonal-cell::before { border-bottom-width: 50px; border-right-width: 80px; }
}
scope="col" 明確表頭範圍aria-hidden="true" 於偽元素/SVG<style>
.diag { position:relative; min-width:90px; height:50px; border-right:1px solid #ccc; border-bottom:1px solid #ccc; }
.diag::before { content:""; position:absolute; inset:0; border-bottom:50px solid transparent; border-right:90px solid #eee; z-index:-1; }
.diag .row { position:absolute; bottom:6px; left:6px; font-size:.8rem; font-weight:600; }
.diag .col { position:absolute; top:6px; right:6px; font-size:.8rem; font-weight:600; }
</style>
<th class="diag" scope="col">
<span class="row">分類</span>
<span class="col">項目</span>
</th>
三種做法各有優劣:邊框三角形最輕量相容、漸層代碼最少、SVG最銳利可動畫。根據專案相容性需求與設計複雜度選擇,並務必配合語意化標記與無障礙屬性,打造既美觀又可用的表格斜線表頭。