水平居中< ul>导航栏中包含浮动的li元素 [英] Horizontally centering a <ul> navbar that contains floated li elements in it
问题描述
我一直在尝试使用悬停下拉菜单创建一个水平导航栏。我有它的工作,但为了所有的元素在并排(水平),他们必须有float:left应用于他们。有什么办法让他们到中心?
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?
此外,是我的CSS编码风格...正确吗?我觉得我做错了。
谢谢!
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;
}
推荐答案
)可以使用 display:inline-block;
水平居中而不是使用 float:left;
。
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.
a href =http://jsfiddle.net/C5Xdp/1/ =nofollow> http://jsfiddle.net/C5Xdp/1/
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;
}
这篇关于水平居中< ul>导航栏中包含浮动的li元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!