June 18, 2013
Dropdown Menu CSS
Wizzme’s Question:
I cannot figure out what is wrong with my dropdown menu. When I over over the main level link, the drop down appear but at the left of my screen instead of underneath the main link.
I have been on this for a couple of hours and any help would be greatly appreciated.
Here is the html part :
<div class="nav">
<ul id="menu">
<li><a href="#" class="current">Home</a></li>
<li><a href="#">Apetiziers</a>
<ul>
<li><a href="#">Sub-Link 1</a></li>
<li><a href="#">Sub-Link 2</a></li>
<li><a href="#">Sub-Link 3</a></li>
<li><a href="#">Sub-Link 4</a></li>
</ul>
</li>
<li><a href="#">Entree</a>
<ul>
<li><a href="#">Sub-Link 1</a></li>
<li><a href="#">Sub-Link 2</a></li>
<li><a href="#">Sub-Link 3</a></li>
<li><a href="#">Sub-Link 4</a></li>
</ul>
</li>
<li><a href="#">Main Course</a>
<ul>
<li><a href="#">Sub-Link 1</a></li>
<li><a href="#">Sub-Link 2</a></li>
<li><a href="#">Sub-Link 3</a></li>
<li><a href="#">Sub-Link 4</a></li>
</ul>
</li>
<li><a href="#">Dessert</a>
<ul>
<li><a href="#">Sub-Link 1</a></li>
<li><a href="#">Sub-Link 2</a></li>
<li><a href="#">Sub-Link 3</a></li>
<li><a href="#">Sub-Link 4</a></li>
</ul>
</li>
<li><a href="#">Contact Us</a></li>
</ul>
</div>
And the .css :
ul#menu {
float: left;
margin: 0;
width: auto;
padding: 0px 40px 0px;
background: #333; color: #fff;
line-height: 100%;
}
ul#menu li {
display: inline;
}
/* top level link */
ul#menu a {
float: left;
padding: 10px 16px;
margin-right: 0px;
background: #789; color: #fff;
text-decoration: none;
border-right: 1px solid #e2e2e2;
}
/* main level link hover */
ul#menu a.current {
background: #f60; color: #fff;
}
ul#menu li:hover > a {
color: #fff; background: #ff4500;
text-decoration: underline;
}
/* dropdown */
ul#menu li:hover > ul {
display: block; /* shows the sub-menu (child ul of li) on hover */
}
/* sub level list */
ul#menu ul {
display: none; /* hides the sub-menu until you hover over it */
margin: 0;
padding: 0;
width: 140px;
position: absolute;
top: 35px;
left: 0;
background: #000;
border: solid 1px #ccc;
}
ul#menu ul li {
float: none;
margin: 0;
padding: 0;
}
ul#menu ul a {
font-weight: normal;
background: #9BB3BF; color: #036;
}
/* sub levels link hover */
ul#menu ul li a:hover {
color: #036; background: #DDDF99;
}
It is probably jumping towards the closest relative container. So configure your list to act as relative container:
ul#menu > li {
position: relative;
}
Also there was unnecessary float
in your anchor tags, your li are already set to display as inline
there is no point in float them
ul#menu a {
display: inline-block;
padding: 10px 16px;
/* ... */
}
Here your fixed code