I created a navbar and used sticky to fix the navbar at the top of the webpage. The problem is, when sticky is being activated, it is push the image below it a bit. How do I prevent this from happening? I thought the problem was because of differences in how I used position property but I have a similar code that is working with no problems. Also, will help if anyone can share how to make the sticky transition smooth and seamless. I am attaching part of code for the same
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");
}
.main-navbar {
display: inline-flex;
width: 100%;
max-width: 800px;
position: relative;
padding-bottom: 17px;
left: 20%;
top: 0px;
}
/*Code for Sticky*/
.sticky {
position: fixed;
top: 10px;
background-color: white;
z-index: 99999999;
transition: 0.3s top ease-in-out;
-webkit-transition: 0.3s top ease-in-out;
-moz-transition: 0.3s top ease-in-out;
-ms-transition: 0.3s ease-in-out;
-o-transition: 1s ease-in-out;
animation: faceInEffect 0.3s;
-webkit-animation: faceInEffect 0.3s;
box-shadow: -1px 2px 4px rgb(110, 109, 109);
}
@keyframes faceInEffect {
from {
top: 0px;
}
to {
top: 10px;
}
}
.hero>img {
position: relative;
top: 6.7rem;
left: 4.5rem;
}
<div class="main-navbar" id="navbar">
<nav>
<ul class="nav-list">
<li class="dropdown-item-1">
<a href="">Men</a>
<ul class="sub-menu">
<li><a href="#">shirts</a> </li>
</ul>
</li>
</ul>
</nav>
</div>
<div class="contentforscroll>
src=" https://static.nike.com/a/images/f_auto/dpr_1.0,cs_srgb/w_906,c_limit/83f15213-514a-4963-a765-74c379b89a34/nike-just-do-it.png "
alt=" " style="width: 1300px; ">
<img src="https://static.nike.com/a/images/f_auto/dpr_1.0,cs_srgb/w_906,c_limit/83f15213-514a-4963-a765-74c379b89a34/nike-just-do-it.png "
alt=" " style="width: 1300px; ">></img>
</div>
2
Answers
You have this problem because – your nav section is out of Normal Flow when sticky. You need to wrap your
<div class="main-navbar" id="navbar">
div with height = height .main-navbar.css
You can do this with
position:sticky;
And it’s not necessary to use css animation.