當元素 width: 0; height: 0 時,四條 border 相交形成**四個三角形**。將三邊設為透明,保留一邊顏色,即得單一三角形。
.triangle-up {
width: 0; height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-bottom: 10px solid #666; /* 顏色在底邊 → 朝上三角 */
}
.triangle-down { border-top: 10px solid #666; }
.triangle-left { border-right: 10px solid #666; }
.triangle-right { border-left: 10px solid #666; }
.tooltip {
position: relative;
display: inline-block;
}
.tooltip::after {
content: "";
position: absolute;
bottom: 100%; left: 50%;
margin-left: -6px; /* 箭頭寬度一半 */
border-width: 6px;
border-style: solid;
border-color: transparent transparent #333 transparent; /* 朝上 */
}
.tooltip::before {
content: attr(data-tip);
position: absolute;
bottom: calc(100% + 12px); left: 50%;
transform: translateX(-50%);
padding: 4px 8px;
background: #333; color: #fff;
border-radius: 4px;
white-space: nowrap;
font-size: 0.75rem;
}
border-style: dashed 代替 transparent 解決 IE6-7 邊框顏色洩漏。font-size: 0; line-height: 0; 消除行高干擾。.triangle-modern {
width: 20px; height: 20px;
background: #666;
clip-path: polygon(50% 0%, 0% 100%, 100% 100%); /* 朝下三角 */
}
優點:支援漸變背景、陰影、動畫、任意多邊形。缺點:IE 不支援。
<svg width="12" height="8" viewBox="0 0 12 8">
<polygon points="6,0 12,8 0,8" fill="currentColor" />
</svg>
/* CSS: .icon-arrow { width: 12px; height: 8px; } */
優點:無限縮放、可 CSS 變色 (fill: currentColor)、語義清晰、無 Hack。
.arrow::before { content: "▲"; font-size: 0.6em; line-height: 1; }
適用於純裝飾性箭頭,無需額外 DOM/HTTP 請求。
<Triangle direction="up" size={12} color="#666" />
/* 內部自動選擇 clip-path (現代) / border (兼容) / SVG */
抽象平台差異,業務代碼只需聲明「方向、大小、顏色」。
Border 三角形是 CSS 經典奇技淫巧,理解其幾何原理最有價值。**現代專案優先 Clip-path/SVG/Unicode**,僅在極舊環境維護 Border 方案。封裝為通用組件,一次編寫、到處復用。