如何使用 CSS 或 HTML 居中导航栏?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5995405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to center a navigation bar with CSS or HTML?
提问by tokyowp
回答by morgar
#nav ul {
display: inline-block;
list-style-type: none;
}
It should work, I tested it in your site.
它应该可以工作,我在您的网站上对其进行了测试。


回答by Niclas Sahlin
Add some CSS:
添加一些CSS:
div#nav{
text-align: center;
}
div#nav ul{
display: inline-block;
}
回答by Brandon
If you have your navigation <ul>with class #nav
Then you need to put that <ul>item within a div container. Make your div container the 100% width. and set the text-align: element to center in the div container. Then in your <ul>set that class to have 3 particular elements: text-align:center; position: relative; and display: inline-block;
如果您<ul>使用类 #nav 进行导航,那么您需要将该<ul>项目放入div 容器中。使您的 div 容器具有 100% 的宽度。并将 text-align: 元素设置为在 div 容器中居中。然后在您的<ul>设置中,该类具有 3 个特定元素: text-align:center; 位置:相对;并显示:内联块;
that should center it.
那应该居中。
回答by camara
You could also use float and inline-block to center your nav like the following:
您还可以使用 float 和 inline-block 将导航居中,如下所示:
nav li {
float: left;
}
nav {
display: inline-block;
}
回答by AlbertVo
Your navdivis actually centered correctly. But the ulinside is not. Give the ula specific width and center that as well.
您navdiv实际上已正确居中。但ul内部不是。给ul一个特定的宽度和中心。
回答by polas
The best way to fix it I have looked for the code or trick how to center nav menu and found the real solutions it works for all browsers and for my friends ;)
修复它的最佳方法我已经寻找代码或技巧如何将导航菜单居中,并找到了适用于所有浏览器和我的朋友的真正解决方案;)
Here is how I have done:
这是我的做法:
body {
margin: 0;
padding: 0;
}
div maincontainer {
margin: 0 auto;
width: ___px;
text-align: center;
}
ul {
margin: 0;
padding: 0;
}
ul li {
margin-left: auto;
margin-right: auto;
}
and do not forget to set doctype html5
并且不要忘记设置 doctype html5

