Stratboy Stratboy - 5 months ago 12
CSS Question

Why can't an <ul> (with absolute position) inside a <li> (with relative position) auto size?

EDIT: see also my own answer below (2016)




For example:

<ul>
<li class="first"><a href="#" title="">Home</a></li>
<li><a href="#" title="">Chi siamo</a>
<ul><li><a href="#" title="">item1</a></li><li><a href="#" title="">item2</a></li></ul>
</li>
<li><a href="#" title="">Novità</a></li>
<li><a href="#" title="">Promozioni</a></li>
</ul>


Then styled:

/* level 1 Main menu ----------------------------------------- */

#main-menu > ul{ list-style:none; }

#main-menu > ul > li{
float:left;
display:block;
position:relative;
margin-left:1em;
}

#main-menu > ul > li.first{
margin-left:0;
}


/* sub Main menu ----------------------------------------- */

#main-menu > ul > li ul {
position: absolute;
z-index:1000;
display:none;
left:0;
top:28px;
}

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

#main-menu > ul > li ul li{
float:left;
display:block;
list-style:none;
}


ok. So, I've got the main menu that shows up horizontal. I also want the submenu to show horizontal. But for some reason, the ul box do not resize to reach the total li tags width, so it remains vertical. The parent ul do not suffer of this problem.
I could make it work by simply adding a proper width to the child ul, but this is not the way I wanna use.

Any idea?

Answer

It's important to have the :hover twice if you use position absolute; 1st on the li, that triggers the display: block, then on the ul that is shown on trigger.
And then keep positioning and styling separate: I styled the a and not the li

See here: http://jsfiddle.net/HerrSerker/T8x2r/2/

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

Should work with float:left also http://jsfiddle.net/T8x2r/3/