Contents

css的小箭頭原理

CSS border 繪製三角形的原理

CSS 的 border 屬性在元素寬高為零時,會顯示出四個三角形。這是因為四邊 border 的交界處本來就是斜角切割的,只是在正常情況下因為元素有寬高,這個特性並不明顯。

原理示意

當元素的 widthheight 都是 0 時:

1
2
3
4
5
6
7
8
.triangle-demo {
  width: 0;
  height: 0;
  border-top: 50px solid red;
  border-right: 50px solid blue;
  border-bottom: 50px solid green;
  border-left: 50px solid yellow;
}

你會看到四個三角形分別指向四個方向,各佔一角。

製作各方向三角形

要製作指向某方向的三角形,就把該方向的對面 border 設為有色,其他三邊設為 transparent

向上三角形(▲)

1
2
3
4
5
6
7
.triangle-up {
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-bottom: 40px solid #333;  /* 底部有色 = 三角形朝上 */
}

向下三角形(▼)

1
2
3
4
5
6
7
.triangle-down {
  width: 0;
  height: 0;
  border-left: 20px solid transparent;
  border-right: 20px solid transparent;
  border-top: 40px solid #333;  /* 頂部有色 = 三角形朝下 */
}

向右三角形(▶)

1
2
3
4
5
6
7
.triangle-right {
  width: 0;
  height: 0;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
  border-left: 40px solid #333;  /* 左邊有色 = 三角形朝右 */
}

向左三角形(◀)

1
2
3
4
5
6
7
.triangle-left {
  width: 0;
  height: 0;
  border-top: 20px solid transparent;
  border-bottom: 20px solid transparent;
  border-right: 40px solid #333;  /* 右邊有色 = 三角形朝左 */
}

實際應用場景

Tooltip 氣泡框

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
.tooltip {
  position: relative;
  background: #333;
  color: #fff;
  padding: 8px 12px;
  border-radius: 4px;
}

/* 向下的箭頭 */
.tooltip::after {
  content: '';
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  border-top: 8px solid #333;
}
1
2
3
4
5
6
7
8
9
.dropdown-arrow {
  display: inline-block;
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 6px solid currentColor;
  vertical-align: middle;
}

現代替代做法:CSS clip-path

現代瀏覽器支援 clip-path,可以更直觀地裁切元素形狀:

1
2
3
4
5
6
.triangle-clippath {
  width: 60px;
  height: 60px;
  background: #333;
  clip-path: polygon(50% 0%, 0% 100%, 100% 100%);  /* 向上三角形 */
}
方法 優點 缺點
border trick 支援所有瀏覽器 需要 width/height 為 0,不直觀
clip-path 直觀、彈性高 IE 不支援

參考資料