萬盛學電腦網

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

CSS 垂直導航菜單:多級列表、滑動門背景、狀態樣式完整實現

HTML 結構:語義化巢狀列表

<div id="navcontainer">
  <ul id="navlist">
    <li id="active"><a href="#" id="current">Item one</a>
      <ul id="subnavlist">
        <li id="subactive"><a href="#" id="subcurrent">Subitem one</a></li>
        <li><a href="#">Subitem two</a></li>
        <li><a href="#">Subitem three</a></li>
        <li><a href="#">Subitem four</a></li>
      </ul>
    </li>
    <li><a href="#">Item two</a></li>
    <li><a href="#">Item three</a></li>
    <li><a href="#">Item four</a></li>
  </ul>
</div>

CSS 核心樣式

#navcontainer { margin-left: 30px; }
#navcontainer ul { margin: 0; padding: 0; list-style: none; font-family: verdana, arial, sans-serif; }
#navcontainer li { margin: 0; }

/* 一級選單 */
#navcontainer a {
  display: block; width: 140px; padding: 5px 10px;
  color: #000; background-color: #adc1ad;
  text-decoration: none; font-weight: bold; font-size: .8em;
  border-top: 1px solid #fff; border-left: 1px solid #fff;
  border-bottom: 1px solid #333; border-right: 1px solid #333;
  background-image: url(images/vertical06.jpg); background-repeat: no-repeat; background-position: 0 0;
}
#navcontainer a:hover {
  background-color: #889e88; color: #000;
  border-top: 1px solid #333; border-left: 1px solid #333;
  border-bottom: 1px solid #fff; border-right: 1px solid #fff;
  background-image: url(images/vertical06a.jpg);
}

/* 二級選單 */
#navcontainer ul ul a {
  width: 125px; padding: 5px 5px 5px 30px; /* 縮進 30px */
  background-color: #c5d8c5; font-weight: normal;
  border: none; background-image: none;
}
#navcontainer ul ul a:hover { background-color: #889e88; }

關鍵技巧解析

  1. `display: block`** 讓 `` 填滿 `
  2. `,整個區域可點擊。
  3. 邊框立體感**:上/左亮色、下/右暗色模擬凸起;Hover 反轉邊框色模擬按下。
  4. 背景圖切換**`vertical06.jpg` → `vertical06a.jpg` 實現狀態圖標變化 (滑動門精靈圖更佳)。
  5. 二級縮進**`padding-left: 30px` + `width` 縮減,視覺層級清晰。
  6. 當前頁高亮**`#current`、`#subcurrent` 可單獨定義 `background: #fff; color: #c00;` 等。

現代化重構:純 CSS 下拉/側滑

/* 隱藏子菜單 */
#navcontainer ul ul { display: none; }
/* Hover 顯示 */
#navcontainer li:hover > ul { display: block; position: absolute; left: 100%; top: 0; }
/* 或側邊欄展開 */
#navcontainer li input[type="checkbox"]:checked ~ ul { display: block; } /* Checkbox Hack */

配合 `transition: max-height 0.3s` 實現平滑展開動畫,無需 JS。

無障礙增強

  • `
  • 當前頁 `aria-current="page"`。
  • 鍵盤可操作:`Tab` 進入、`Enter/Space` 展開子菜單、`Esc` 關閉。
copyright © 萬盛學電腦網 all rights reserved