htmlcssbootstrap-5hamburger-menu

I'm trying to create a functional Hamburger icon, in a HTML & CSS file. But it's not colapsing, like it is supposed to


I'm a beginner and trying my hand at Bootstrap. The bootstrap navbar is not working as is supposed to in a responsive screen. Help me rectify my mistake.

<!DOCTYPE html>

<html>
  <head>
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.
min.css"
      integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2"
      crossorigin="anonymous"
    />
  </head>

  <body>
    <nav class="navbar navbar-light">
      <div class="container-fluid">
        <h2>Posts</h2>

        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarItems">
          <span class="navbar-toggler-icon"></span>
        </button>

        <div class="navbar-collapse" id="navbarItems">
          <ul class="navbar-nav">
            <li class="nav-item"><a class="nav-link" href="#">Feed</a></li>
            <li class="nav-item"><a class="nav-link" href="#">Week</a></li>
            <li class="nav-item"><a class="nav-link" href="#">Month</a></li>
            <li class="nav-item"><a class="nav-link" href="#">Year</a></li>
            <li class="nav-item"><a class="nav-link" href="#">Infinity</a></li>
            <li class="nav-item"><a class="nav-link" href="#">Latest</a></li>
          </ul>
        </div>
      </div>
    </nav>

    <script
      src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
      integrity="sha384DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx"
      crossorigin="anonymous"
    ></script>
  </body>
</html>

Had provided the whole code, was trying that when I'll click the hamburger icon, it will collapse & clicking again will reopen it.


Solution

  • I see some of the missing attributes and classes in your HTML try adding this to your html it should work.

    Also, you are using the wrong attribute in the button.

    // This
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarItems">
      <span class="navbar-toggler-icon"></span>
    </button>
    
    // To This
    <button
      class="navbar-toggler"
      type="button"
      data-toggle="collapse"
      data-target="#navbarItems"
      aria-controls="navbarTogglerDemo03"
      aria-expanded="false"
      aria-label="Toggle navigation"
    >
      <span class="navbar-toggler-icon"></span>
    </button>
    
    
    // This
    <div class="navbar-collapse" id="navbarItems"></div>
    
    // To This 
    <div class="collapse navbar-collapse" id="navbarItems"></div>
    

    Hope this works for you :)