萬盛學電腦網

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

CSS 面包屑導航欄兩種實現方案(CSS3 箭頭 / 相容 IE6)

方案一:現代 CSS3 箭頭形狀(IE9+)

HTML

<nav id="crumbs" aria-label="麵包屑">
  <ul>
    <li><a href="#">首頁</a></li>
    <li><a href="#">產品分類</a></li>
    <li><a href="#">子分類</a></li>
  </ul>
</nav>

CSS 關鍵:偽元素構建三角形

#crumbs ul { display: flex; list-style: none; margin: 0; padding: 0; }
#crumbs li { margin-right: 8px; }
#crumbs a {
  position: relative; display: inline-block; padding: 0 20px 0 30px;
  height: 34px; line-height: 34px; background: #f66fa2; color: #fff;
  text-decoration: none; font-size: 14px;
}
#crumbs a::before,
#crumbs a::after {
  content: ""; position: absolute; top: 0;
  border: 17px solid transparent; /* 高度一半 */
  border-left-width: 0;
}
#crumbs a::before { left: -17px; border-right-color: #fff; z-index: 2; } /* 內側白三角,切割左側 */
#crumbs a::after  { right: -17px; border-right-color: #f66fa2; z-index: 1; } /* 外側色三角,形成箭頭 */
#crumbs li:first-child a { padding-left: 20px; border-radius: 4px 0 0 4px; }
#crumbs li:first-child a::before { display: none; }
#crumbs li:last-child a  { padding-right: 30px; border-radius: 0 4px 4px 0; }
#crumbs li:last-child a::after { display: none; }
#crumbs a:hover { background: #e56592; }
#crumbs a:hover::after { border-right-color: #e56592; }

方案二:CSS2.1 邊框三角形(IE6+ 相容)

.crumb { display: inline-block; *display: inline; *zoom: 1; font: bold 14px/32px Arial; }
.crumb li { float: left; position: relative; z-index: 2; width: 200px; text-align: center; }
.crumb li em { /* 外層白三角 */
  position: absolute; right: -24px; top: -8px; width: 0; height: 0; line-height: 0;
  border: 24px dashed transparent; border-left: 24px solid #fff; border-left-style: solid;
}
.crumb li i { /* 內層色三角 */
  position: absolute; right: -16px; top: 0; width: 0; height: 0; line-height: 0;
  border: 16px dashed transparent; border-left: 16px solid #f0f0f0; border-left-style: solid;
}
.crumb li.current { background: #f60; color: #fff; }
.crumb li.current i { border-left-color: #f60; }

選型建議

  • 新專案:方案一(語義化 <nav>、Flex、偽元素、動畫過渡)。
  • 老舊專案必須支援 IE6/7:方案二(無偽元素、純邊框三角、條件註釋可隔離)。
  • 無障礙:加上 aria-current="page" 標記當前頁,配合 [aria-current] { font-weight: bold; }。
copyright © 萬盛學電腦網 all rights reserved