OiO.lk Blog CSS How to smoothly transition between absolute and fixed positions on a navbar during scroll?
CSS

How to smoothly transition between absolute and fixed positions on a navbar during scroll?


I’m trying to implement a navbar that switches from position: absolute to position: fixed when the user scrolls down more than 160 pixels. My goal is to have a smooth transition between these two states, but I’m struggling to make it work as I expect.

Currently, the change between absolute and fixed happens abruptly, and I can’t seem to make the transition feel smooth, since CSS doesn’t allow animating the position property.

Here’s what I’ve tried so far:

.navbar-absolute {
    position: absolute;
    top: 0;
    width: 100%;
    z-index: 999;
    transition: all 0.5s ease;
    background-color: rgba(255, 255, 255, 0.76); /* Semi-transparent background */
    box-shadow: none;
    opacity: 0.9;
}

.navbar-fixed {
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 999;
    background-color: rgb(255, 255, 255); /* Solid white background */
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3); /* Shadow when scrolling */
    opacity: 1;
}

JS:

let lastScrollTop = 0;
const navbar = document.querySelector('.navbar');

window.addEventListener('scroll', function () {
    let scrollTop = window.pageYOffset || document.documentElement.scrollTop;

    if (scrollTop === 0) {
        navbar.classList.remove('navbar-fixed');
        navbar.classList.add('navbar-sticky');
    } else if (scrollTop > 160 && scrollTop > lastScrollTop) {
        navbar.classList.remove('navbar-sticky');
        navbar.classList.add('navbar-fixed');
    }
});



You need to sign in to view this answers

Exit mobile version