掌握橫向下拉後,縱向版本邏輯相通,關鍵在於子選單定位:相對定位父容器 + 絕對定位子選單,確保滑鼠互動時位置精準對齊。
ul {
margin: 0; padding: 0; list-style: none;
width: 120px; border-bottom: 1px solid #ccc; font-size: 12px;
}
ul li { position: relative; } /* 父 li 設相對定位,作為子選單定位基準 */
li ul {
position: absolute; /* 子選單絕對定位 */
left: 119px; top: 0; /* 緊貼父 li 右側 */
display: none;
}
ul li a {
width: 108px; display: block; text-decoration: none;
color: #666; background: #fff; padding: 5px;
border: 1px solid #ccc; border-bottom: 0;
}
ul li a:hover { background-color: #ddd; }
/* IE6/7 Hack:修正顯示異常 */
* html ul li { float: left; height: 1%; }
* html ul li a { height: 1%; }
/* 顯示邏輯同橫向版 */
li:hover ul, li.over ul { display: block; }
position: relative 不改變元素本身位置,但建立「定位上下文」,子元素 position: absolute 將相對其定位。left: 119px 使子選單貼齊父選單右邊(120px 寬 - 1px 邊框)。
* html ... 只有 IE6/7 能解析,用於修正舊版 IE 的渲染 Bug。詳細用法請搜尋「CSS Hack」。