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;
}
<ul id="top-menu">
<li>something
<ul>
<li>somethingelse1</li>
<li>somethingelse2</li>
</ul>
</li>
<li> ... etc.</li>
</ul>
The code above produces a result similar to this (I had my cursor over “Caps”):
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?
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;
}