Dropdown nav, with menu and submenus centralized: what error am I committing?

-2

I'm having a small problem centering a submenu from a dropdown menu. The following example is fairly simple, but it illustrates my problem well:

<ul id="menu">
    <li>Menu1
    <li>Menu2
        <ul>
            <li>Submenu1
            <li>Submenu2
            <li>Submenu3 com outras palavras
            <li>Submenu4
        </ul>
    <li>Menu3
</ul>

Preview JSFiddle . What happens is as follows: The red submenu (within the second UL) is centered on the parent menu, Menu2 . However, I do not know if it is correct since I had to adjust the left position of the submenu UL (50%) and LI (-50%).

Everything was centralized, regardless of the text size of the menus, but with a problem: bg green shows that the submenu UL is still in the "wrong position", but only so I can centralize perfectly since I did not want to stipulate a width (in pixels) for the submenus.

Is it possible to centralize everything, including the UL sumbenu?

    
asked by anonymous 11.09.2014 / 02:19

1 answer

1
The problem occurs because you're using position: absolute; to center your items within <ul> , so this <ul> takes on the total size of your child items even if you position negatively to the left, plus the <ul> element is not positioned within its corresponding <li> .

The correct structure would look like this:

CSS:

ul#menu {
    margin:0;
    padding: 0;
    position: absolute;
    left: 0;
    right: 0;
    text-align: center;
}

ul#menu > li {
    padding: 10px 20px;
    position: relative;
    display: inline-block;
    border-right: 1px solid;
    text-transform: uppercase;
    background: orange;
}

ul#menu > li:last-child {
    border-right: 0;
}

ul#menu ul {
    padding: 0;
    position: absolute;
    background: green;
    margin-top: 10px;
    margin-left: -20px;
}

ul#menu ul li{
    position: relative;
    list-style: none;
    white-space: nowrap;
    text-transform: none;
    background: tomato;
}

HTML:

<ul id="menu">
    <li>Menu1</li>
    <li>Menu2
        <ul>
            <li>Submenu1</li>
            <li>Submenu2</li>
            <li>Submenu3 com outras palavras</li>
            <li>Submenu4</li>
        </ul>
    </li>
    <li>Menu3</li>
</ul>
    
11.09.2014 / 02:58