Search code examples
htmlcssmenucentersubmenu

Centered CSS menu with submenu


I want to have a centered CSS menu with submenu. I could do a part of it (main menu) but I have problems on showing submenu. When I hover main menu items to show their submenu, problem starts ...

* {
  font-family:arial;
}

#menu {
    height: 65px;
    background: #f3f3f3;
    text-align: center;
}

#menu ul {
    list-style: none;
    text-align: center;
    margin: 0;
    padding: 0;
    position: relative;
    top: 15px
}

#menu ul li {
    list-style: none;
    text-align: center;
    margin-left: 5px;
    margin-right: 5px;
    display: inline;
}

#menu ul li a {
    padding: 4px 10px 6px 10px;
    border-radius: 3px;
    display: inline-block;
    color: #666;
    transition: all 0.3s;
}

#menu ul li a:hover, #menu ul li a:focus, #menu ul li a.active  {
    background: #58c071;
    color: white;
}

.submenu {
  display:none;
  position:absolute;
  top: 5px;
  width: 200px;
  background:white;
}

#menu li:hover > ul {
  display: block
}
<div id="menu" class="text-center">
  <ul>
    <li><a href="">Home</a></li>
    <li><a href="">Products</a>
      <ul class="submenu">
        <li><a href="">Product 1</a></li>
        <li><a href="">Product 2</a></li>
        <li><a href="">Product 3</a></li>
      </ul>
    </li>
    <li><a href="">Contact</a></li>
  </ul>
</div>

https://jsfiddle.net/e8wyp6et/1/

Do you have any idea?


Solution

  • You have to have position: relative; on the submenu's closest parent and left: 0; on the .submenu selector :

    In your question, it was added to the #menu ul which positioned the submenu relative to that.

    #menu ul li  {
      position: relative;
    }
    

    and

    .submenu {
      display:none;
      position:absolute;
      top: 5px;
      left: 0; /*this is needed to tell the submenu to align to the left of li*/
      width: 200px;
      background:white;
    }
    

    https://jsfiddle.net/Kyle_/e8wyp6et/2/