In this scenario, the goal is to create a navigation bar that remains at the bottom of the viewport when the page loads. As the user scrolls down, the bar should scroll upwards and become fixed to the top of the page.
HTML and CSS:
<li><a href="#">Home</a></li> <li><a href="#">Services</a></li> <li><a href="#">Contact</a></li></p> <p></ul><br></div></p> <pre class="brush:php;toolbar:false">#nav-container { position: relative; bottom: 0; width: 100%; background-color: #202020; z-index: 10; } .nav-menu { list-style-type: none; display: flex; justify-content: center; } .nav-menu > li { margin: 0 10px; } .nav-menu > li > a { color: #ffffff; text-decoration: none; padding: 10px 15px; border-radius: 5px; } .sticky { position: fixed; top: 0; }
JavaScript:
const menuElement = document.getElementById("nav-container"); window.addEventListener("scroll", () => { if (window.scrollY > 100) { menuElement.classList.add("sticky"); } else { menuElement.classList.remove("sticky"); } }); ```` This code adds the "sticky" class to the navigation bar element when scrolling down more than 100 pixels. When scrolling back up to a point where it's no longer fixed, the "sticky" class is removed. **CSS:**
/Sticky state styling /
.sticky {
background-color: #ffffff;
box-shadow: 0px 2px 5px 0px rgba(0, 0, 0, 0.2);
}
This styling can be customized to match the desired appearance of the fixed navigation bar.
The above is the detailed content of How to Create a Sticky Navigation Bar in Bootstrap?. For more information, please follow other related articles on the PHP Chinese website!