我有一个粘性顶部导航栏,在滚动时我想保持可见,并且在所有其他内容上方。我在页面上设置了position: relative
的内容,以便可以在其周围放置其他元素。当我这样做时,相对内容在滚动时会忽略导航栏并将其重叠。有什么方法可以让我的页面内容相对定位,并且仍然可以观察到粘性导航栏?
我尝试给相对内容的上边距等于导航栏的高度。
.nav-bar {
position: sticky;
top: 0px;
font-family: Arial, Helvetica, sans-serif;
border-bottom: solid rgb(179, 173, 173) 1px;
background-color: rgb(255, 255, 255);
}
.nav-bar #title {
margin: 0;
font-size: 2em;
padding-left: 2%;
}
.test-class #test-content {
width: 500px;
height: 500px;
background-color: rgb(70, 67, 67);
position: absolute;
}
<div class="nav-bar">
<p id="title">Title</p>
</div>
<div class="test-class">
<p id="test-content"></p>
</div>
预期:粘性标头停留在所有其他内容之上。
实际:当内容的位置设置为相对时,内容与标题重叠。
答案 0 :(得分:0)
尝试一下。从position:absolute
类中删除.test-class #test-content
。可以根据需要正常工作。
.nav-bar{
position:sticky;
top:0px;
font-family: Arial, Helvetica, sans-serif;
border-bottom:solid rgb(179, 173, 173) 1px;
background-color: rgb(255, 255, 255);
}
.nav-bar #title{
margin:0;
font-size: 2em;
padding-left: 2%;
}
.test-class #test-content {
width:500px;
height:500px;
background-color:rgb(70, 67, 67);
}
<body>
<div class="nav-bar">
<p id="title">Title</p>
</div>
<div class="test-class">
<p id="test-content"></p>
</div>
</body>
答案 1 :(得分:0)
如果您希望导航栏始终保持可见状态,只需为其设置一个大于内容的Z索引即可
.nav-bar{
position:sticky;
top:0px;
font-family: Arial, Helvetica, sans-serif;
border-bottom:solid rgb(179, 173, 173) 1px;
background-color: rgb(255, 255, 255);
z-index: 1
}
答案 2 :(得分:0)
您可以使用此代码
body {
margin: 0;
padding: 0;
}
.nav-bar {
overflow: hidden;
background-color: #333333;
position: sticky;
top: 0;
width: 100%;
}
.nav-bar #title {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 20px;
text-decoration: none;
font-size: 25px;
margin: 0;
}
.test-class {
padding: 16px;
margin-top: 0px;
height: 1500px;
}
.test-class #test-content {
width: 500px;
height: 500px;
background-color: rgb(70, 67, 67);
margin: 0;
}