居中横向CSS菜单 [英] Center a horizontal CSS menu

查看:93
本文介绍了居中横向CSS菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用以下CSS的CSS菜单。

I have a CSS menu using the following CSS.

将整个菜单置于页面上的最佳方式是什么?

What is the best way to center the whole menu on the page?

我曾尝试在< nav> 之外使用另一个< div> 并设置页边距但是它的正确排列一直都在。

I have tried using another <div> outside <nav> and setting margins but its just aligning left all the time.



nav {
    margin: 0 auto; 
    text-align: center;
    border:1px solid black;
}

nav ul ul {
    display: none;
}

nav ul li:hover > ul {
    display: block;
}

nav ul {
    list-style: none;
}

nav ul li {
    float: left;
}

nav ul li:hover a {
    color: #000000;
}

nav ul li a {
    display: block; 
    padding: 10px 15px;
    color: #000000;
    text-decoration: none;
}       

nav ul ul {
    border-radius: 0px;
    padding: 0;
    position: absolute;
}

nav ul ul li {
    float: none; 
    border-top: 1px solid #000000;
    border-bottom: 1px solid #000000;
    position: relative;
}

nav ul ul li a {
    color: #000000;
}

nav ul ul li a:hover {
    color: #666666;
}

nav ul ul ul {
    position: absolute;
    top:0;
}

jsfiddle: http://jsfiddle.net/njuVm/

jsfiddle : http://jsfiddle.net/njuVm/

推荐答案

使用以下CSS规则导航栏:

You can center the navigation bar by using the following CSS rules:

nav {
    margin: 0 auto; 
    text-align: center;
    border:1px solid black;
}

nav ul ul {
    display: none;
}

nav ul li:hover > ul {
    display: block;
}

nav ul {
    list-style: none;
    margin: 0;                 /* << add this */
    padding: 0;                /* << add this */
    display: inline-block;     /* << add this */
    vertical-align: top;       /* << add this */
}

nav ul li {
    float: left;
    margin: 0;          /* << add this */
    padding: 0;         /* << add this */
}

nav ul li:hover a {
    color: #000000;
}

nav ul li a {
    display: block; 
    padding: 10px 15px;
    color: #000000;
    text-decoration: none;
    background-color: pink; /* optional... */
}       

nav ul ul {
    border-radius: 0px;
    padding: 0;
    position: absolute;
}

nav ul ul li {
    float: none; 
    border-top: 1px solid #000000;
    border-bottom: 1px solid #000000;
    position: relative;
}

nav ul ul li a {
    color: #000000;
}

nav ul ul li a:hover {
    color: #666666;
}

nav ul ul ul {
    position: absolute;
    top:0;
}

参见演示: http://jsfiddle.net/audetwebdesign/DP6Ax/

关键是将 display:inline-block for nav ul ,这将允许您的 text-align:center code>规则生效。

The key is to set display: inline-block for nav ul, which will allow your text-align: center rule to take effect.

请确保将 ul 的边距和填充 li 元素。你所做的一切或多或少都是正确的,所以你应该很好。

Make sure to zero out margins and paddings on the ul and li elements. Everything else that you did was more or less right, so you should be good.

这篇关于居中横向CSS菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆