【css】導航欄小結(一)-----簡單導航
阿新 • • 發佈:2019-02-13
導航欄=連結列表
導航條基本上是一個連結列表,所以使用 <ul> 和 <li>
元素非常有意義:
1).垂直導航欄
只需要設定<a>
元素的樣式,就可以建議一個垂直導航欄。
注意請務必指定 <a>
元素在垂直導航欄的的寬度。如果省略寬度,IE6可能產生意想不到的效果。
css:
<style>
ul
{
list-style-type:none;
margin:0;
padding:0;
}
a:link,a:visited
{
display:block;
font-weight:bold ;
color:#FFFFFF;
background-color:#98bf21;
width:120px;
text-align:center;
padding:4px;
text-decoration:none;
text-transform:uppercase;
}
a:hover,a:active
{
background-color:#7A991A;
}
</style>
啟用/當前導航條例項
在點選了選項後,我們可以新增 “active” 類來標準哪個選項被選中:
.active {
background-color : #4CAF50;
color: white;
}
html:
<ul>
<li><a href="#home" class="active ">主頁</a></li>
<li><a href="#news">新聞</a></li>
<li><a href="#contact">聯絡</a></li>
<li><a href="#about">關於</a></li>
</ul>
2).水平導航欄
有兩種方法建立橫向導航欄。使用內聯(inline)或浮動(float)的列表項。
這兩種方法都很好,但如果你想連結具有相同的大小,你必須使用浮動的方法。
2.1 使用內聯
css:
ul
{
list-style-type:none;
margin:0;
padding:0 6px; /*注意:如果您只為 a 元素設定內邊距(而不設定 ul 元素),那麼連結會出現在 ul 元素之外。所以,我們為 ul 元素添加了 top 和 bottom 內邊距*/
}
li
{
display:inline;
}
a:link,a:visited
{
font-weight:bold;
color:#FFFFFF;
background-color:#98bf21;
text-align:center;
padding:6px;
text-decoration:none;
text-transform:uppercase;
}
a:hover,a:active
{
background-color:#7A991A;
}
html:
<!--li不換行則無邊距縫隙,換行了就有。因為是內聯元素,設定了dispaly:inline具有文字屬性的緣故-->
<ul>
<li><a href="#home">主頁</a></li>
<li><a href="#news">新聞</a></li>
<li><a href="#contact">聯絡</a></li>
<li><a href="#about">關於</a></li>
</ul>
2.2 使用浮動 —— 正文內容注意清除浮動
css:
<style>
ul {
list-style-type: none;
/**注意: overflow:hidden 新增到 ul 元素,以防止 li 元素列表的外出。.**/
overflow: hidden;
}
li {
/**注意: 如果 !DOCTYPE 沒有定義, floating 可以產生意想不到的結果.**/
float: left;
}
a {
display: block;
width: 100px;
font-weight: bold;
color: #FFFFFF;
/**背景顏色新增到連結中顯示連結的區域。整個連結區域是可點選的,不僅僅是文字。**/
background-color:#98bf21;
text-align: center;
padding:6px;
text-decoration: none;
text-transform: uppercase;
}
a:hover,
a:active {
background-color: #7A991A;
}
</style>
html:
<ul>
<li>
<a href="#home">Home</a>
</li>
<li>
<a href="#news">News</a>
</li>
<li>
<a href="#contact">Contact</a>
</li>
<li style="float:right">
<a class="active" href="#about">關於</a>
</li>
</ul>
3).全屏高度的固定導航條 :一個左邊是全屏高度的固定導航條,右邊是可滾動的內容
ul {
list-style-type: none;
margin: 0;
padding: 0;
width: 25%;/**設定寬度:便於fixed定位**/
background-color: #f1f1f1;
position: fixed;/**固定左側:fixed定位**/
height: 100%; /* 全屏高度 */
overflow: auto; /* 如果導航欄選項多,允許滾動 */
}
li a {
display: block;
color: #000;
padding: 8px 16px;
text-decoration: none;
}
li a.active {
background-color: #4CAF50;
color: white;
}
/**注意這裡的寫法not(.active)即hover時候不包括active當前li**/
li a:hover:not(.active) {
background-color: #555;
color: white;
}
固定導航條
可以設定頁面的導航條固定在頭部或者底部:
position: fixed; 配合top|bottom|left|right 進行定位
/**固定在頭部或者腳步**/
ul {
position: fixed;
top: 0; /*bottom: 0;*/
width: 100%;
}