如何創建:固定菜單
學習如何使用 CSS 創建“固定”菜單。
如何創建固定的頂部菜單
第一步 - 添加 HTML:
<div class="navbar"> <a href="#home">Home</a> <a href="#news">News</a> <a href="#contact">Contact</a> </div> <div class="main"> <p>Some text some text some text some text..</p> </div>
第二步 - 添加 CSS:
要創建固定在頂部的菜單,請使用 position:fixed
和 top:0
。請注意,固定菜單將覆蓋您的其他內容。要解決這個問題,請在內容上方添加一個等于或大于菜單高度的上外邊距(margin-top)。
/* 導航欄 */ .navbar { overflow: hidden; background-color: #333; position: fixed; /* 將導航欄設置為固定位置 */ top: 0; /* 將導航欄置于頁面頂部 */ width: 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%; /* 全寬 */ } /* Main content */ .main { margin-bottom: 30px; /* 添加下外邊距以避免內容重疊 */ }
相關頁面
教程:CSS 導航欄