Horizontally centering a <ul> navbar that contains floated li elements in it

房东的猫 提交于 2019-12-07 21:23:52

问题


I've been trying to make a horizontal navbar with hover dropdown menus. I've got it working but in order for all of the elements in the to stay side by side (horizontal), they have to have float:left applied to them. Is there any way to get them to center?

Also, is my CSS coding style...correct? I feel like I'm doing this wrong. Thanks!

HTML:

<div id="navbar" class="titlereg">
    <ul>
        <li><a href="#">Reviews</a>
                <ul>
                    <li><a href="#">DnB</a></li>
                </ul>
            </li>

            <li><a href="#">Opinions</a></li>
            <li><a href="#">About</a></li>
        </ul>
</div>

CSS:

#navbar {
    width:500px;
    display:block;
    margin-left:auto;
    margin-right:auto;
}

#navbar ul {
    list-style:none;
    padding:0;
}

#navbar ul li {
    float:left;
}

#navbar ul li a {
    text-decoration:none;
    font-size: 1.5em;
    padding-right:5px;
    color:rgba(255,0,180,0.5);
}

#navbar ul li a:hover {
    color:rgba(0,168,255,0.5);
}

#navbar ul li ul li {
    visibility:hidden;
}

#navbar ul li:hover > ul li{
    visibility:visible;
}

回答1:


You can accomplish block(ish)-level elements that can be horizontally centered by using display: inline-block; instead of using float: left;.

If you absolutely position your submenu to its relative parent, you can position it more easily.

http://jsfiddle.net/C5Xdp/1/

#navbar {
    width:500px;
    display:block;
    margin-left:auto;
    margin-right:auto;
    text-align: center;
}

#navbar ul {
    list-style:none;
    padding:0;
    display: inline;
}

#navbar ul li { position: relative;
    display: inline;
}

#navbar ul li a {
    display: inline-block;
    text-decoration:none;
    font-size: 1.5em;
    padding-right:5px;
    color:rgba(255,0,180,0.5);
}

#navbar ul li a:hover {
    color:rgba(0,168,255,0.5);
}

#navbar ul li ul { position: absolute;
    left: 0;
    top: 1em; }

#navbar ul li ul li {
    visibility:hidden;
}

#navbar ul li:hover > ul li{
    visibility:visible;
}



回答2:


Use below code

#navbar ul {
    list-style:none;
    padding:0;
    text-align:center;
}

#navbar ul li {
    display:inline-block;

}



回答3:


#navbar ul li ul li {
visibility: hidden;
text-align: center;
right: 0;
display: block;
width: 100%;
}



回答4:


Just to be different, I find this works pretty well, and avoids some of the uncertainty that using inline-block creates:

#navbar ul {
    display: table;
    list-style: none;
    margin: 0 auto;
    padding: 0;
}

#navbar ul li {
    float: left;
}


来源:https://stackoverflow.com/questions/20487328/horizontally-centering-a-ul-navbar-that-contains-floated-li-elements-in-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!