表格左上角表頭需斜線分隔,上半部分顯示「屬性」,下半部分顯示「項目」,常見於報表、數據透視表。
<style>
.table-diag { position: relative; border-collapse: collapse; }
.table-diag th.diag {
position: relative;
padding: 0; width: 100px; height: 40px;
border: 1px solid #333;
}
.table-diag th.diag::before {
content: "";
position: absolute; top: 0; left: 0; right: 0; bottom: 0;
border-bottom: 40px solid transparent;
border-right: 100px solid #333; /* 斜線顏色/粗細通過 border 模擬 */
/* 更精細控制:用 linear-gradient 畫 1px 斜線 */
}
.table-diag th.diag span { position: relative; z-index: 1; display: flex; flex-direction: column; justify-content: space-between; height: 100%; padding: 4px; font-size: 12px; }
.table-diag th.diag span.attr { align-self: flex-end; text-align: right; }
.table-diag th.diag span.item { align-self: flex-start; text-align: left; }
</style>
<table class="table-diag">
<tr>
<th class="diag"><span class="attr">屬性</span><span class="item">項目</span></th>
<th>Q1</th><th>Q2</th>
</tr>
<tr><th scope="row">華東</th><td>120</td><td>135</td></tr>
</table>
進階:用 linear-gradient 畫 1px 斜線,避免 border 粗細難控制:
.diag::before {
content: "";
position: absolute; inset: 0;
background: linear-gradient(to top right, transparent calc(50% - 0.5px), #333 calc(50% - 0.5px), #333 calc(50% + 0.5px), transparent calc(50% + 0.5px));
}
.diag-cell {
position: relative;
background:
linear-gradient(to top right, transparent 49.5%, #333 49.5%, #333 50.5%, transparent 50.5%),
linear-gradient(to bottom left, transparent 49.5%, #333 49.5%, #333 50.5%, transparent 50.5%);
/* 文字定位 */
}
.diag-cell .attr { position: absolute; top: 4px; right: 8px; }
.diag-cell .item { position: absolute; bottom: 4px; left: 8px; }
<th class="diag-svg">
<svg viewBox="0 0 100 40" style="width:100%; height:100%;">
<line x1="0" y1="40" x2="100" y2="0" stroke="#333" stroke-width="1.5"/>
<text x="90" y="10" text-anchor="end" font-size="8" fill="#333">屬性</text>
<text x="10" y="34" font-size="8" fill="#333">項目</text>
</svg>
</th>
const canvas = document.createElement('canvas');
canvas.width = 100; canvas.height = 40;
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#333'; ctx.lineWidth = 1.5;
ctx.beginPath(); ctx.moveTo(0, 40); ctx.lineTo(100, 0); ctx.stroke();
ctx.font = '12px sans-serif'; ctx.fillStyle = '#333';
ctx.textAlign = 'end'; ctx.fillText('屬性', 95, 14);
ctx.textAlign = 'start'; ctx.fillText('項目', 5, 34);
th.diagCanvas.style.backgroundImage = `url(${canvas.toDataURL()})`;
| 方案 | 優點 | 缺點 | 推薦場景 |
|---|---|---|---|
| Border 三角形 | 無額外標籤、IE9+ 全支持 | 斜線粗細/銳度受限、文本定位需微調 | 簡單靜態表頭、兼容舊瀏覽器 |
| Linear Gradient | 代碼極少、無偽元素、易維護 | 漸變 1px 線在高 DPI 可能模糊 | 現代項目首選 |
| Inline SVG | 矢量無失真、可動畫、語義清晰 | HTML 體積略增、需內聯或引用 | 高精度、需動畫/交互 |
| Canvas | 像素級控制 | 需 JS、設備像素比處理麻煩、不可選中文本 | 已有 Canvas 渲染管線 |
斜線純裝飾,務必用兩個 <span> 或 <abbr> 承載「屬性/項目」文本**,供螢幕閱讀器朗讀;SVG 方案可直接用 <text> 並加 aria-hidden="true" 隱藏裝飾線。