CSS Navigation menu slides to right when hovering

2019-08-03 05:10发布

问题:

I have a navigation menu and I wanted to have a dropdown menu for subpages. I created it and everything is ok except that the pages links in the top menu slide over to the right when the dropdown shows when I hover the page link with subpages. What is it that I am missing here? Thanks for the help in advance.


Here is the jsfiddle: jsfiddle.net/AC8XK/

What I have is not 100% like that, since there is a lot missing, but it shows exactly the problem I mentioned.


I managed to get the menu working properly. The solution to the initial problem was, as mike said, changing the dropdown ul position from relative to absolute.

As for the positioning of the dropdown, I solved the problem by using padding-top instead of top or margin-top.

Thanks to everyone that tried to help.

回答1:

The code you supplied in jsfiddle was..well...a bit of a mess. I had to strip a lot of it down and generate some base formatting for the dropdown. I will comment the important bits, but it should be more or less copy & paste. The code is solely the layout text for the menu - no visual or positional styling stuff.

Key Concepts: 1 - Set your LIs to width:auto and the li>ul to position: absolute;width:100%. This allows positioning and makes sure the individual ul ul lis are on separate lines. 2- You had the display:none and display:block correct. Alternatively, you can use off-the-screen positioning for the same purpose. 3- Remember to do ul ul {position:absolute;} to allow positioning of the submenus relative to the parent li!

HTML:

<div class="greenbar">
<nav>
    <ul id="menu-navigation-menu" class="navigation">
        <li id="menu-item-107" class="menu-item"><a href="#">About</a>
            <ul class="sub-menu">
                <li id="menu-item-116" class="menu-item"><a href="#">Terms of Use</a></li>
                <li id="menu-item-119" class="menu-item"><a href="#">Just another link</a></li>
            </ul>
        </li>
        <li id="menu-item-106" class="menu-item"><a href="#">Services</a>
            <ul class="sub-menu">
                <li id="menu-item-120" class="menu-item"><a href="#">Another link again</a></li>
            </ul>
        </li>
        <li id="menu-item-105" class="menu-item"><a href="#">Clients</a></li>
        <li id="menu-item-104" class="menu-item"><a href="#">Resources</a></li>
    </ul>
</nav>
</div> 

CSS:

nav ul {
list-style-type: none;
position: relative;
display: inline-table;
}
nav ul li {float: left;}
nav ul li a { display: block; text-decoration: none;}
nav ul ul {
display: none;
position: absolute;
width: auto;
}
nav ul li:hover > ul { display: block;}
nav ul ul li { width: 100%;}


标签: css menu hover