-1

我正在尝试将包含 ul 菜单的菜单居中。

菜单向左浮动,我似乎无法将菜单置于屏幕中间。

HTML

<section>
    <nav>
        <ul> 
            <li><a href='#'>item1</a></li>
            <li><a href='#'>item2</a></li>
            <li><a href='#'>item3</a></li>
            <li><a href='#'>item4</a></li>
            <li><a href='#'>item5</a></li>
        </ul>
    </nav>
</section>

CSS

nav ul{
    display: inline-block;
    background-color: red;
}
nav ul li{
    list-style: none;
    font:bold .6em arial;
    float: left;
    margin: .3em;
    padding: 1.3em;
    background-color: #A8A8A8;
}

//the and margin text align doesn't seem to work...
section {
   text-align:center;
   margin:0 auto;
}

任何人都可以帮助我吗?非常感谢!

4

6 回答 6

2

正如 xec 所指出的,问题似乎出在无效的注释语法上。CSS 中注释的正确语法是/*Comment Here */. 更正注释语法后,您的代码确实使菜单居中。

/*the and margin text align doesn't seem to work...*/
section {
   text-align:center;
   margin:0 auto;
 }

演示

于 2013-08-16T06:55:01.777 回答
1

如果您不特别关心 IE 7 及以下版本(仅部分支持inline-block- 请参阅http://caniuse.com/inline-block),这可行,并且具有使链接更容易点击的优点:http ://jsfiddle.net/V97tR/1/

nav
{
    text-align:center;
}

nav ul{
    display: block;
    background-color: red;
}
nav ul li{
    display:inline-block;
    list-style: none;
    font:bold .6em arial;
    margin: .3em;
    background-color: #A8A8A8;
}

nav ul li a
{
    display:block;
    padding: 1.3em;
}
于 2013-08-16T07:30:33.500 回答
1

你没有给nav. 内部navsection一个块,因此无论您是否提供容器,它将是其容器的整个宽度margin:0 auto

解决方法:赋予navsection. 或者,完全删除section,因为这里没有必要。

于 2013-08-16T06:57:32.017 回答
0

您可以使用弹性盒:

section {
   text-align:center;
   margin:0 auto;
   display: flex;
 }

这是一个小提琴:http: //jsfiddle.net/2c8LB/

于 2013-08-16T06:53:32.923 回答
0

尝试这个:

JSFiddle

#wrapper {
    float:left;
    width:100%;
    background:#fff;
    overflow:hidden;
    position:relative;
}
nav ul {
    clear:left;
    float:left;
    list-style:none;
    margin:0;
    padding:0;
    position:relative;
    left:50%;
    text-align:center;
}
nav ul li {
    list-style: none;
    font:bold .6em arial;
    float: left;
    background-color: red;
    display:block;
    list-style:none;
    margin:0;
    padding:5px;
    position:relative;
    right:50%;
}
nav ul li a {
    display:block;
    margin:0 0 0 1px;
    padding:3px 10px;
    background:#ddd;
    color:#000;
    text-decoration:none;
    line-height:1.3em;
}
于 2013-08-16T07:08:31.600 回答
0

像这样

演示

CSS

nav ul{
    display: inline-block;
    background-color: red;
    margin:0;
    padding:0;
}
nav ul li{
    list-style: none;
    font:bold .6em arial;
    float: left;
    margin: .3em;
    padding: 1.3em;
    background-color: #A8A8A8;
}

/*the and margin text align doesn't seem to work...*/
section {
   text-align:center;
   margin:0 auto;
 }
于 2013-08-16T07:09:54.220 回答