Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sub-menu position in a simple drop-down menu

Let’s assume we have a simple nested menu in HTML:

<ul id="top-menu">
 <li>something
  <ul>
   <li>somethingelse1</li>
   <li>somethingelse2</li>
  </ul>
 </li>
 <li> ... etc.

And equally simple CSS that allows you to display submenus when you move the cursor to any position:

    #top-menu ul {
        display: none;
    }

    #top-menu li:hover > ul {
        display: block;
    }

    #top-menu {
        list-style: none;
        padding: 0;
        margin: 0;
        position: relative;
    }

    #top-menu > li {
        position: relative;
        padding: 10px;
        cursor: pointer;
    }

    #top-menu > li > ul {
        position: absolute;
        top: 0;
        left: 25%;
        list-style: none;
        background-color: #fff;
        padding: 0;
        margin: 0;
        z-index: 1000;
        min-width: 150px;
    }

    #top-menu > li > ul > li {
        padding: 10px;
        background-color: #ffffff;
        cursor: pointer;
    }

    #top-menu > li > ul > li > ul {
        position: absolute;
        top: 0;
        left: 25%;
        list-style: none;
        background-color: #fff;
        padding: 0;
        margin: 0;
        z-index: 1000;
    }

The code above produces a result similar to this (I had my cursor over "Caps"):
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

As you can see, when I select the “Caps” item, the first submenu item is at the same height as the parent item.
What would I need to fix in the code so that no matter what item on the main menu I select, the first submenu item is at the same height as the first item on the main menu?

>Solution :

To fix this, you can remove the position: relative from #top-menu > li
From this code:

    #top-menu > li {
        position: relative; /* remove this line */
        padding: 10px;
        cursor: pointer;
    }

To this code:

    #top-menu > li {
        padding: 10px;
        cursor: pointer;
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading