如何创建:固定菜单
学习如何使用 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 导航栏