純 CSS 畫三角形是每個前端都該會的基本功。它可以用在對話框的指向箭頭、下拉選單的展開提示,甚至圖表上。學會之後,很多原本要切圖的小元素都能省下來。
當一個元素的寬高都設為 0,而四邊卻有粗邊框時,這四條邊框會在中心點相遇,各自形成一個三角形。

如果替四條邊框分別指定不同顏色,這個結構會看得很清楚:

接著把內容清空(寬高為 0、font-size 為 0),四個三角形就完整露出來了:

最後,只保留想要的那一個方向。要頂部的三角形,就把 left、right、bottom 三條邊設為透明:

換個顏色配置,就能得到朝上、朝下、朝左、朝右四種箭頭:

核心樣式只有幾行:
float: left;
border-style: solid;
border-width: 10px;
border-color: #000 #ccc #ccc #ccc;
height: 0;
width: 0;
font-size: 0;
為什麼要寫 font-size: 0 與 line-height: 0?這是為了兼容部分舊版瀏覽器在空元素上仍保留最小行高的行為。
下拉選單或提示框常需要一個「指向」的小尾巴。做法是外層放一個 <s> 當外框(顏色同邊框線),內層 <i> 當內框(顏色同背景),兩者錯開 1px,就能做出帶描邊的箭頭。


div.container {
position: absolute;
top: 30px;
left: 40px;
font-size: 9pt;
display: block;
height: 100px;
width: 200px;
background-color: transparent;
*border: 1px solid #666;
}
s {
position: absolute;
top: -20px;
*top: -22px;
left: 20px;
display: block;
height: 0;
width: 0;
font-size: 0;
line-height: 0;
border-color: transparent transparent #666 transparent;
border-style: dashed dashed solid dashed;
border-width: 10px;
}
i {
position: absolute;
top: -9px;
*top: -9px;
left: -10px;
display: block;
height: 0;
width: 0;
font-size: 0;
line-height: 0;
border-color: transparent transparent #fff transparent;
border-style: dashed dashed solid dashed;
border-width: 10px;
}
.content {
border: 1px solid #666;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
position: absolute;
background-color: #fff;
width: 100%;
height: 100%;
padding: 5px;
box-shadow: 3px 3px 4px #999;
}
<div class="container">
<div class="content">
<br>這是框中的文字,可動態顯示,高度會自動增加。
</div>
<s><i></i></s>
</div>
這裡刻意用 dashed 而非 solid,是為了避開某些舊瀏覽器在邊框交界處留下的細小接縫。
<div class="demo"><span class="bottom-arrow"></span></div>
.demo { position: relative }
.bottom-arrow {
position: absolute;
top: 10px;
left: 0px;
border-style: solid;
border-width: 100px;
border-color: #000000 transparent transparent transparent; /* 上邊框設為想要的顏色 */
height: 0;
width: 0;
font-size: 0;
_border-color: #000000 tomato tomato tomato; /* 透明色 for IE6 */
_filter: chroma(color=tomato); /* 透明色 for IE6 */
}
如果不需要透明效果,直接把 border-color 設成目標顏色即可,也就不必為 IE6 寫那兩行 hack。chroma 是 IE 專屬的濾鏡屬性,可把指定顏色視為透明,語法為 filter: chroma(color=color),只有一個參數。以今日的瀏覽器水準而言,這段相容性代碼已可安全移除;若真的需要帶描邊的箭頭,改用 clip-path 或旋轉過的方形會更好維護。