Use position: sticky to make navbar sticky

This commit is contained in:
Helen Chong 2024-04-18 22:54:20 +08:00
parent 69312040f3
commit e0e8f9acb5
1 changed files with 2 additions and 29 deletions

View File

@ -12,6 +12,8 @@
padding: 0 0.6rem; padding: 0 0.6rem;
width: 100%; width: 100%;
z-index: 999; z-index: 999;
position: sticky;
top: 0;
} }
.navbar a { .navbar a {
@ -37,33 +39,4 @@
flex-wrap: wrap; flex-wrap: wrap;
gap: 0.5rem; gap: 0.5rem;
} }
/* Added to the navbar with JS when it reaches its scroll position */
.nav--sticky {
position: fixed;
width: 100%;
top: 0;
}
/* Add some top padding to the page content to prevent sudden quick movement
as the navigation bar gets a new position at the top of the page
(position:fixed and top:0) */
.nav--sticky + main {
padding-top: 2rem;
}
</style> </style>
<script defer>
// Make the navigation bar sticky
// const hero = document.querySelector(".hero");
const navbar = document.querySelector(".navbar");
window.addEventListener("scroll", () => {
const scrollPosition = window.scrollY || document.documentElement.scrollTop;
const stickyLine = hero.scrollHeight - navbar.scrollHeight;
if (scrollPosition > stickyLine + 100) {
navbar.classList.add("nav--sticky");
} else {
navbar.classList.remove("nav--sticky");
}
});
</script>