所以我正在尝试将导航栏添加到我的论坛网站并遇到一些问题。
示例:Example Gif
这是我正在使用的代码
<div id="navbar">
<a href="/">HOME</a>
<a href="/news">NEWS</a>
<a href="/forum">FORUM</a>
<a href="/members">MEMBERS</a>
<a href="/shop">SHOP</a>
</div>
<style>
#navbar {
overflow: hidden;
background-color: #2b3c4e;
z-index: 100; /* <-- Added */
padding-left: 270px;
}
#navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 25px 16px;
text-decoration: none;
font-size: 17px;
}
#navbar a:hover {
background-color: #FFA500;
color: black;
}
#navbar a.active {
background-color: #4CAF50;
color: white;
}
.content {
padding: 16px;
}
.sticky {
position: fixed;
top: 0;
width: 100%
}
.sticky + .content {
padding-top: 60px;
}
</style>
<script>
window.onscroll = function() {myFunction()};
var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
</script>
答案 0 :(得分:1)
像这样修改你的CSS。通过使标记为内嵌块,您可以将它们与text-align:center
对齐,您不需要填充左侧。设置html,正文和导航栏宽度:100%使其拉伸页面的宽度以处理第二个问题。 :
html,body{width:100%; margin:0}
#navbar {
overflow: hidden;
background-color: #2b3c4e;
z-index: 100; /* <-- Added */
text-align:center;
width:100%;
}
#navbar a {
color: #f2f2f2;
text-align: center;
padding: 25px 16px;
text-decoration: none;
font-size: 17px;
display:inline-block;
}
此外,如果你添加它,你的标题将在滚动时显示页面的宽度。
.sticky {
position: fixed;
top: 0;
left:0;
right:0;
}
答案 1 :(得分:0)
尝试删除CSS中的padding-left。
<div id="navbar">
<a href="/">HOME</a>
<a href="/news">NEWS</a>
<a href="/forum">FORUM</a>
<a href="/members">MEMBERS</a>
<a href="/shop">SHOP</a>
</div>
<style>
#navbar {
overflow: hidden;
background-color: #2b3c4e;
z-index: 100; /* <-- Added */
}
#navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 25px 16px;
text-decoration: none;
font-size: 17px;
}
#navbar a:hover {
background-color: #FFA500;
color: black;
}
#navbar a.active {
background-color: #4CAF50;
color: white;
}
.content {
padding: 16px;
}
.sticky {
position: fixed;
top: 0;
width: 100%
}
.sticky + .content {
padding-top: 60px;
}
</style>
<script>
window.onscroll = function() {myFunction()};
var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
</script>
&#13;