如何操作 - 固定選單
瞭解如何使用 CSS 建立一個“固定”的選單。
如何建立固定的頂部選單
步驟 1) 新增 HTML
示例
<div class="navbar">
<a href="#home">主頁</a>
<a href="#news">新聞</a>
<a href="#contact">聯絡</a>
</div>
<div class="main">
<p>一些文字,一些文字,一些文字,一些文字...</p>
</div>
步驟 2) 新增 CSS
要建立固定的頂部選單,請使用 position:fixed
和 top:0
。請注意,固定選單會覆蓋您其他的內容。要解決此問題,請為內容新增一個等於或大於選單高度的 margin-top
。
示例
/* 導航欄 */
.navbar {
overflow: hidden;
background-color: #333;
position: fixed; /* 設定導航欄為固定位置 */
top: 0; /* 將導航欄定位在頁面頂部 */
width: 100%; /* 寬度 100% */
}
/* 導航欄中的連結 */
.navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
/* 滑鼠懸停時更改背景 */
.navbar a:hover {
background: #ddd;
color: black;
}
/* 主要內容 */
.main {
margin-top: 30px; /* 新增頂部邊距以避免內容重疊 */
}
自己動手試一試 »
如何建立固定的底部選單
要建立固定的底部選單,請使用 position:fixed
和 bottom:0
。
示例
/* 導航欄 */
.navbar {
position: fixed; /* 設定導航欄為固定位置 */
bottom: 0; /* 將導航欄定位在頁面底部 */
width: 100%; /* 寬度 100% */
}
/* 主要內容 */
.main {
margin-bottom: 30px; /* 新增底部邊距以避免內容重疊 */
}
自己動手試一試 »
提示:訪問我們的 CSS 導航欄教程 瞭解更多關於導航欄的資訊。