DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
DIV+CSS 雙層選單:主導覽列搭配子選單的排版技巧
編輯:CSS詳解     

很多網站的導覽列是「兩層」的:上面一排主要分類,緊接在下方一排是該分類的子項目。用 CSS 實作這種結構,重點不在選單本身,而在 z-index 與邊框配色的層次安排。

主選單

#navcontainer
{
  margin: 0;
  padding: 0 0 0 12px;
}
#navcontainer UL
{
  list-style: none;
  margin: 0;
  padding: 0;
  border: none;
}
#navcontainer LI
{
  display: block;
  margin: 0;
  padding: 0;
  float: left;
  width: auto;
}
#navcontainer A
{
  color: #444;
  display: block;
  width: auto;
  text-decoration: none;
  background: #DDDDDD;
  margin: 0;
  padding: 2px 10px;
  border-left: 1px solid #fff;
  border-top: 1px solid #fff;
  border-right: 1px solid #aaa;
}
#navcontainer A:hover, #navcontainer A:active { background: #BBBBBB; }

每個 a 的左側與上方用亮色(#fff)、右側用暗色(#aaa),這是一九九〇年代介面設計的經典手法:亮暗成對出現,元素看起來就像微微凸起。滑過時整塊換成 #BBBBBB,是目前選中的暗示。

子選單

#subnav
{
  position: relative;
  top: -1px;            /* 往上疊 1px,蓋住主選單的下緣 */
  z-index: 101;
  margin: 0;
  padding: 0px 0 3px 0;
  background: #BBBBBB;
  border-top: 1px solid #fff;
  border-bottom: 1px solid #aaa;
}
#subnav UL
{
  list-style: none;
  margin: 1px 0 0px 13px;
  padding: 0px;
  border-right: 1px solid #fff;
  border-left: 1px solid #aaa;
}
#subnav LI
{
  position: relative;
  z-index: 102;
  display: block;
  margin: 0;
  padding: 0;
  float: left;
  width: auto;
}
#subnav A
{
  color: #fff;
  display: block;
  width: auto;
  text-decoration: none;
  margin: 0;
  padding: 2px 12px 2px 10px;
}
#subnav A:hover, #subnav A:active { color: #444; }
#subnav BR, #navcontainer BR { clear: both; }

三個關鍵數字

top: -1px 讓子選單往上 overlap 一像素,兩列之間不會出現意外的白縫,視覺上黏成一體。

子選單的 z-index: 101 與項目的 z-index: 102 則處理重疊時的前後關係:整個子選單在背景之上,而子項目又比子選單的邊框更上層,邊框才不會切到文字。

最後 BR { clear: both; } 清除浮動。因為兩列都用 float: left,若不收乾淨,後面的內容會往上貼。

HTML

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

實作提醒

範例中的 id="active" 與 id="current" 用來標示目前所在位置,但 id 必須唯一,多個選單同時存在時會衝突。改用 class="active" 並搭配 :focus 樣式,可以同時解決合規與鍵盤操作兩個問題。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved