Centering a UL menu of unknown width, overflow iss

2019-02-20 07:35发布

问题:

I created a simplified demo of what I'm looking to accomplish but basically, when I resize (smaller) I get scrollbars I would like to remove.

Adding overflow: hidden to the nav element works...until I want to add in sub-menus.

http://jsfiddle.net/aKUAP/

HTML

<nav>
    <ul>
        <li><a href="#">Menu Item</a></li>
        <li><a href="#">Menu Item</a></li>
        <li><a href="#">Menu Item</a></li>
        <li><a href="#">Menu Item</a></li>
    </ul>
</nav>
<p>Looking for a way to hide the scrollbars created when the page is resized smaller. Using overflow:hidden on the nav element will hide any sub-menus used downt he line.</p>

CSS

nav {
    position: relative;
    zoom: 1;    
    border-top: 1px solid #ccc;
    border-bottom: 3px solid #ccc;    
    float: left;
    width: 100%;
    /*overflow: hidden; */
}
ul {
    clear: left;
    float: left;
    position: relative;
    left: 50%;
    text-align: center;
}
ul li {
    float: left;
    position: relative;
    right: 50%;
}
ul a {
    padding: 5px;
    font-size: 11px;
    display: block;   
}
p {
    text-align: center;
    padding: 30px;
}

Maybe there's a better technique for centering a UL menu of unknown items at 100% width?

回答1:

You could switch to using overflow-x: hidden: http://jsfiddle.net/aKUAP/2/

Maybe there's a better technique for centering a UL menu of unknown items at 100% width?

Yes, there is. Switch to using display: inline-block on the ul, and text-align: center on nav: http://jsfiddle.net/aKUAP/3/