Search code examples
cssdrop-down-menudropdownnavbarbootstrap-5

bootstrap, navbar and dropdown content positioning


The problem is the drop-down behavior (here's the codepen to the problematic html, the original layout was taken from here).

<header class="pb-3">
  <nav class="navbar navbar-expand-md navbar-light bg-white border-bottom">
    <div class="d-flex w-100 navbar-collapse">
      <ul class="navbar-nav me-auto mb-2 mb-md-0">
        <li>
          <div style="width: 100px; height: 100px">
            <a href="#">
              <img src="../static/store_logo.png" alt="logo" />
            </a>
          </div>
        </li>
        <li class="nav-item dropdown">
          <a class="nav-link dropdown-toggle d-none d-md-block fw500" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
            Product categories
          </a>

          <ul class="dropdown-menu rounded-0 border-0">
            <a href="#">
              <li>Foo</li>
            </a>
            <a href="#">
              <li>Bar</li>
            </a>
            <a href="#">
              <li>Baz</li>
            </a>
          </ul>
        </li>
      </ul>
    </div>
  </nav>
</header>

In the original source the problem is hidden by the fact that a logo image/placeholder inside the nav > .navbar ul is tiny. When I used a larger image, it becomes manifest (I used a div with fixed 100 by 100 px to mimic it in the pen). The problem is the behavior of a drop-down in the same nav. The list of items in .dropdown-menu (ul) doesn't attach to the bottom of the .dropdown-toggle element - instead it's attached to the bottom of the .navbar-nav ul. Which, naturally, is affected by the size of the li containing the image/placeholder.

Being a css noob, I don't know what is the real cause of the problem. Is it a conflict beyween some of the bootstrap classes? I even tried adding a z-index to the .dropdown-menu ul, to no avail. Basic dropdown example in the Bootstrap docs doesn't seem to require any additional tweaks - but there's no navs/navbars involved in there (not to mention a dozen other parent elements).

Thank you all for your time!


Solution

  • Please add this custom css and check agian.

    body .navbar-expand-md .navbar-nav .dropdown-menu {
        top: 30px !important;
    }