Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

html-lists

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?

like image 504
Luca Reghellin Avatar asked Jan 14 '11 13:01

Luca Reghellin


2 Answers

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/

like image 181
yunzen Avatar answered Sep 28 '22 03:09

yunzen


Elements with position: absolute take up the size of their children.

You can either set width: 100%; on the ul, or set left: 0; right: 0; which will also stretch it to the right size.

Also you might want to set list-style:none; on the nested ULs as well as top one.

like image 33
kapa Avatar answered Sep 28 '22 03:09

kapa