<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
position: fixed;
top: 0;
width: 100%;
}
li {
float: left;
}
li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
li a:hover:not(.active) {
background-color: #111;
}
.active {
background-color: #4CAF50;
}
</style>
</head>
<body>
<ul>
<li><a class="active" href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
<div style="padding:20px;margin-top:30px;background-color:#1abc9c;height:1500px;">
<h1>Fixed Top Navigation Bar</h1>
<h2>Scroll this page to see the effect</h2>
<h2>The navigation bar will stay at the top of the page while scrolling</h2>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
<p>Some text some text some text some text..</p>
</div>
</body>
</html>
在我的代码中,我想要一个固定的导航栏。 &#34; ul&#34;标签是我体内的第一件事,所以当我设置&#34; position:fixed&#34;它应该在顶部,但它不是。我不得不指定&#34; top:0&#34;为了那个原因。我发现与我的div相关的样式导致了这个问题。我不明白div为何会以这种方式行事。
如果您不明白我的意思,请删除&#34; top:0&#34;来自与&#34; ul&#34;相关的风格你会在顶部看到一条白色条纹。白色条带是因为为div指定的边距。 我只是想知道,为什么白色条带在那里?还因为如果我没有指定&#34; top:0&#34;我的导航栏低于这个边缘。
另外, 当我说'#34; position:fixed&#34;我还必须指定as&#34; width:100%&#34;。但没有位置属性&#34; ul&#34;默认情况下是&#34; 100%&#34;