麵包屑(breadcrumb)告訴使用者「你現在在哪、怎麼回去」,是層級稍深的網站必備元件。網路上找方法多半得靠一堆小圖拼出箭頭,其實純 CSS 也能做得很漂亮。這裡提供兩種寫法,其中一種還能向下相容舊版 IE。

結構非常簡單,一個 ul 加幾個 li 就好:
<div id="crumbs">
<ul>
<li><a href="#">首頁</a></li>
<li><a href="#">目錄</a></li>
<li><a href="#">子目錄</a></li>
</ul>
<div class="fixed"></div>
</div>
先處理浮動與基本外觀:
#crumbs ul li { float: left; list-style: none; }
#crumbs ul li a {
display: block; float: left; height: 34px; background: #f66fa2;
text-align: center; padding: 10px 20px 0 45px;
position: relative; margin: 0 10px 0 0;
}
關鍵在偽元素做出的箭頭:
#crumbs ul li a:after {
content: ""; position: absolute; right: -22px; top: 0; z-index: 1;
border-top: 22px solid transparent;
border-bottom: 22px solid transparent;
border-left: 22px solid #f66fa2;
}
#crumbs ul li a:before {
content: ""; position: absolute; left: 0; top: 0;
border-top: 22px solid transparent;
border-bottom: 22px solid transparent;
border-left: 22px solid #fff;
}
原理是把一個零尺寸元素的上下邊框設為透明、左邊框設為實色,三邊交會處就形成一個三角形。:after 畫在右側、顏色與該筆相同,作為「箭頭」;:before 畫在左側、顏色與背景相同,蓋出「凹口」,兩者疊合就得到連鎖箭頭的效果。
最後處理頭尾:第一筆用:first-child 加上左側圓角並隱藏 :before(因為它沒有前驅),最後一筆用:last-child 加上右側圓角並隱藏 :after(因為它後面沒東西);hover 時改背景色,:after 的 border-left-color 要一起改,箭頭才不會顏色不一;再補 transition: all 0.2s ease 讓換色柔和。收尾用 .fixed { clear: both; } 清掉浮動。
舊版 IE 不支援偽元素,於是改用兩個空標籤 em 與 i 各畫一個三角形:em 畫顏色較深的底層三角、i 畫上層三角,兩者錯開幾像素就做出帶描邊的效果。
.demo { width: 600px; margin: 100px auto; background: #f0f0f0; position: relative; }
.demo li { float: left; width: 200px; text-align: center; position: relative; z-index: 2; font-weight: bold; font-size: 14px; line-height: 32px; }
.demo li em { position: absolute; right: -24px; top: -8px; width: 0; height: 0; border-width: 24px 0 24px 24px; border-color: transparent transparent transparent #fff; border-style: dashed dashed dashed solid; }
.demo li i { position: absolute; right: -16px; top: 0; width: 0; height: 0; border-width: 16px 0 16px 16px; border-color: transparent transparent transparent #f0f0f0; border-style: dashed dashed dashed solid; }
.demo li.current { background: #f60; color: #fff; z-index: 1; }
.demo li.current i { border-color: transparent transparent transparent #f60; }
HTML 就是三個 li,每個裡面放 <em></em><i></i>,當前所在頁多一個 class="current"。border-style 用 dashed 而非 solid,是為了避開某些舊瀏覽器在零尺寸元素上繪製斜邊時出現的鋸齒。
現在做專案請直接用方法一,程式碼乾淨、不必額外標籤、方便客製顏色。方法二留著是為了理解「零尺寸元素 + 三邊框」這個經典技巧的來源。另外别忘了麵包屑該用 nav 包起來並加上 aria-label="麵包屑",最後一項當前頁不宜做成連結,語意上才正確。