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;
}
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.
#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;
}
Use below code
#navbar ul {
list-style:none;
padding:0;
text-align:center;
}
#navbar ul li {
display:inline-block;
}
#navbar ul li ul li {
visibility: hidden;
text-align: center;
right: 0;
display: block;
width: 100%;
}
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