想在提示框、下拉選單或工具提示上加個三角形箭頭?過去常得準備各種顏色、方向的圖片,維護起來相當麻煩。所幸 MooTools 核心開發者 Darren Waddell 分享了一個絕妙技巧:只需寥寥幾行 CSS,就能畫出任意顏色、大小、方向的三角形,且完美相容所有主流瀏覽器。
將元素的 width 與 height 設為 0,再給予粗邊框。當兩側邊框設為透明(transparent),指向方向的邊框設為實色,三角形便自然形成。邊框越粗,三角形越大;顏色由實色邊框決定。
/* 向上箭頭 */
.arrow-up {
width: 0; height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-bottom: 5px solid #2f2f2f; /* 底色即三角形顏色 */
font-size: 0; line-height: 0;
}
/* 向下箭頭 */
.arrow-down {
width: 0; height: 0;
border-left: 5px solid transparent;
border-right: 5px solid transparent;
border-top: 5px solid #2f2f2f;
font-size: 0; line-height: 0;
}
/* 向左箭頭 */
.arrow-left {
width: 0; height: 0;
border-bottom: 5px solid transparent;
border-top: 5px solid transparent;
border-right: 5px solid #2f2f2f;
font-size: 0; line-height: 0;
}
/* 向右箭頭 */
.arrow-right {
width: 0; height: 0;
border-bottom: 5px solid transparent;
border-top: 5px solid transparent;
border-left: 5px solid #2f2f2f;
font-size: 0; line-height: 0;
}

:before / :after 偽元素若容器本身已有其他用途,不想多加標籤,偽元素是最佳選擇。以下範例示範如何為工具提示(tooltip)加上帶陰影效果的向上箭頭:
.tooltip {
position: relative; /* 為絕對定位的偽元素建立參考點 */
/* 其他樣式... */
}
/* 共用設定 */
.tooltip:before,
.tooltip:after {
content: ' ';
position: absolute;
width: 0; height: 0;
border: 10px solid transparent; /* 箭頭大小 */
}
/* 白色主箭頭(上層) */
.tooltip:before {
border-bottom-color: #fff;
top: -19px; left: 255px;
z-index: 2;
}
/* 深色陰影箭頭(下層,稍微偏移) */
.tooltip:after {
border-bottom-color: #333;
top: -24px; left: 255px;
z-index: 1;
}
只需一個偽元素即可畫出箭頭;第二個偽元素可作為陰影或邊框,豐富視覺層次。這招純 CSS、無圖片、易維護,絕對是介面開發的利器。