Home > Web Front-end > CSS Tutorial > How to Create a Sticky Navigation Bar in Bootstrap?

How to Create a Sticky Navigation Bar in Bootstrap?

Patricia Arquette
Release: 2024-12-03 15:14:15
Original
670 people have browsed it

How to Create a Sticky Navigation Bar in Bootstrap?

How to achieve a Sticky Navigation Bar in Bootstrap

Understanding the Problem

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.

Crafting a Sticky Nav Bar

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;
    }
    Copy after login

    Implementing the Fixity

    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:**
    
    Copy after login

    /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.
    
    Copy after login

    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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template