简体   繁体   English

居中的水平导航栏CSS

[英]centered horizontal navigation bar css

I know there are a lot of answers with this subject but it still doesn't work somehow with my code. 我知道这个主题有很多答案,但是对于我的代码还是不起作用。 Every time I try to center the text with text-align center it doesn't work unless I remove float: left, display: inline or display: inline-block. 每次我尝试使用文本对齐中心将文本居中时,除非我删除float:left,display:inline或display:inline-block,否则它将不起作用。 But then I have a vertical centered navigation bar... 但是然后我有一个垂直居中的导航栏...

Can anyone help me with this? 谁能帮我这个?

This is my HTML code: 这是我的HTML代码:

<div class="nav">
    <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="about.html">About</a></li>
        <li><a href="workshop.html">Moviekids festivals</a></li>
    </ul>
</div>

and here is the CSS code: 这是CSS代码:

*{
margin: 0px;
padding: 0px;
}

body {
text-align: center;
font-family: arial;
background-color: white;
}

#wrapper{
width: 960px;
margin: 0 auto;
height: 100%;
text-align: left;
background-color: #1d1d1b;
}

.nav {
background-image:url("img/nav.jpg");
width: 100%;
height: 50px;
display: inline-block;
}

.nav ul {
list-style-type: none;
}

.nav li {
display: inline;
text-align: center;
}

.nav a {
text-decoration: none;
display: inline-block;
color: #1d1d1b;
padding: 10px;
}

You need to set the text-align on the parent element like so: 您需要像这样在父元素上设置text-align:

.nav ul {
  list-style-type: none;
  text-align: center;
}

.nav li {
  display: inline-block;
}

See Demo 观看演示

I just edited your css to acheive what you need 我刚刚编辑了您的CSS以实现您的需求

.nav ul {
    list-style-type: none;
    text-align:center;
}

.nav li {
    display:inline-block;
    text-align: center;
    padding: 10px;
}

.nav a {
    text-decoration: none;
    display: block;
    color: #1d1d1b;  
}

DEMO DEMO

Always avoid using body text-align try using instead for wrapper. 始终避免使用正文文本对齐,而应尝试使用而不是包装器。

Make sure you have mentioned <!DOCTYPE html> on the top of your HTML code. 确保您在HTML代码的顶部提到了<!DOCTYPE html> Otherwise your code seems perfect. 否则,您的代码似乎很完美。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM