萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> Div CSS 教學

CSS 三角形/箭頭實現技巧:Border 技法原理、現代替代方案與實戰組件封裝

核心原理:零寬高元素 + 邊框三角形

當元素 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 箭頭完整實現

.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;
}

IE 兼容性補丁 (IE9-)

  • border-style: dashed 代替 transparent 解決 IE6-7 邊框顏色洩漏。
  • font-size: 0; line-height: 0; 消除行高干擾。
  • 現代專案**建議放棄 IE9- 支援**,代碼更乾淨。

現代替代方案(推薦)

1. Clip-path 多邊形

.triangle-modern {
  width: 20px; height: 20px;
  background: #666;
  clip-path: polygon(50% 0%, 0% 100%, 100% 100%); /* 朝下三角 */
}

優點:支援漸變背景、陰影、動畫、任意多邊形。缺點:IE 不支援。

2. SVG 內聯/背景圖

<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。

3. Unicode 字符 (最輕量)

.arrow::before { content: "▲"; font-size: 0.6em; line-height: 1; }

適用於純裝飾性箭頭,無需額外 DOM/HTTP 請求。

組件封裝建議 (React/Vue/Svelte)

<Triangle direction="up" size={12} color="#666" />
/* 內部自動選擇 clip-path (現代) / border (兼容) / SVG */

抽象平台差異,業務代碼只需聲明「方向、大小、顏色」。

總結

Border 三角形是 CSS 經典奇技淫巧,理解其幾何原理最有價值。**現代專案優先 Clip-path/SVG/Unicode**,僅在極舊環境維護 Border 方案。封裝為通用組件,一次編寫、到處復用。

copyright © 萬盛學電腦網 all rights reserved