Dropdown Nav, with menu and submenus centered: what mistake am I making?

Asked

Viewed 2,182 times

-2

I have a small problem centering a submenu of a dropdown menu. The following example is quite simple, but it illustrates my problem:

<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 the following: The submenu in red (within the second UL) is centered in the parented 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 size of the menu text, but with one problem: green bg shows that the UL submenu is still in the "wrong position", but only so I can centralize perfectly since I did not want to stipulate a fixed width (in pixels) for submenus.

It is possible to centralize everything, including Sumbenu UL?

  • That’s not your problem, but don’t forget to close the <li tags>

  • Quiet, hehehe, I left so just to make the code cleaner. Thanks for the reminder.

1 answer

1

The problem occurs because you are using position: absolute; to center your items within the <ul>, in this way that <ul> assumes the total size of your child items even if you position negatively to the left, plus that element <ul> is not positioned within its <li> correspondent.

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>
  • Thank you very much for the suggestion, but I believe my question was not understood correctly. What I need is to center everything: main menu and submenus - just like in this example: http://jsfiddle.net/vxLfbmy0/ . It turns out that in the example you mentioned the submenu is aligned to the left of the corresponding menu. Note that if I increase the size of the text the submenu grows to the right and not centered, as I need. Anyway thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.