Reputation: 191
I have a sticky top navbar that I want to stay visible and above all other content when scrolling. I have content on the page that I have set to position: relative
so that I can position other elements around it. When I do this, the relative content ignores the navbar when scrolling and overlaps it. Is there any way for my to have my page content positioned relative and still have it observe the sticky navbar?
I've tried giving the relative content a top margin equal to the height of the navbar.
.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>
Expected: sticky header stays above all other content.
Actual: Content overlaps header when its position is set to relative.
Upvotes: 19
Views: 15645
Reputation: 747
you can use this code
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;
}
Upvotes: 0
Reputation: 519
If you want your navbar stay always visible just give it a z-index bigger than your 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);
z-index: 1
}
Upvotes: 11
Reputation: 4251
Try this. Remove position:absolute
from .test-class #test-content
class. It works fine as you want.
.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>
Upvotes: 1