Search code examples
htmlcssnav

How to fix this dropdown navbar


I am writing a navigation bar with a dropdown option.

I have 2 problems: I can't get the dropdown to position properly under the menu, + also when I try to move the mouse to click on the elements in the dropdown submenu it closes as soon as I move. Can anyone suggest a fix?

Thanks

On codepen:

https://codepen.io/-royqooe/pen/GRxaVbm

/* CSS section for home */

.navtop {
  position: relative;
  background-color: #333333;
  height: 50px;
  width: 100%;
  border: 0;
}

.navtop div {
  display: flex;
  margin: 0 auto;
  height: 100%;
}

.navtop div h1,
.navtop div a {
  display: inline-flex;
  align-items: center;
}

.navtop div h1 {
  flex: 1;
  font-size: 24px;
  padding: 0;
  margin: 0;
  margin-left: 2%;
  color: #f5f8ff;
  font-weight: normal;
}

.navtop div a {
  padding: 0 12px;
  text-decoration: none;
  color: #c1c4c8;
  font-weight: bold;
}

.navtop div a i {
  padding: 2px 8px 0 0;
}

.navtop div a:hover {
  color: #66ccff;
}


/* sequel for home and navbar */

nav.navtop {
  font-family: monospace;
}

.navtop>.navbar>ul {
  list-style: none;
  margin: 0;
  padding-left: 0;
}

.navtop li {
  display: block;
  float: left;
  padding: 0.5rem 0;
  position: relative;
  text-decoration: none;
  transition-duration: 0.3s;
}

.navtop ul li ul {
  background: red;
  visibility: hidden;
  opacity: 0;
  min-width: 5rem;
  position: absolute;
  transition: all 0.5s ease;
  margin-top: 1rem;
  left: 0;
  display: none;
}

.navtop ul li:hover>ul,
.navtop ul li ul:hover {
  visibility: visible;
  opacity: 1;
  display: block;
}

.navtop ul li ul li {
  clear: both;
  width: 100%;
}

@media screen and (max-width: 760px) {
  .topbar-text {
    display: none;
  }
}
<nav class="navlol navtop" role="navigation">
  <div class="navbar">
    <h1>Websitee Title</h1>

    <ul>
      <li><a href="home.php"><i class="fa-solid fa-file"></i><span class="topbar-text">Home</span></a></li>
      <li><a href="#">Two</a>
        <ul class="dropdownnn">
          <li><a href="#">Sub-1</a></li>
          <li><a href="#">Sub-2</a></li>
          <li><a href="#">Sub-3</a></li>
        </ul>
      </li>
      <li class="navelements"><a href="#">Three</a></li>
      <li><a href="profile.php"><i class="fas fa-user-circle"></i><span class="topbar-text">Profile</span></a></li>
      <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i><span class="topbar-text">Logout</span></a></li>
    </ul>
  </div>
</nav>


Solution

  • got an easy fix for you:

    add this

    .navtop li {
      min-height:25px;
    }
    

    the issue is that that menu li was way shorter than the others to the sides due to the icons, even better maybe is instead adding this instead:

    .navtop li {
      height:100%
    }
    

    both worked for me