Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center a horizontal CSS menu

Tags:

html

css

I have a CSS menu using the following CSS.

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

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/

like image 223
user2710234 Avatar asked May 27 '26 14:05

user2710234


1 Answers

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;
}

See demo at: http://jsfiddle.net/audetwebdesign/DP6Ax/

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

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.

like image 119
Marc Audet Avatar answered May 30 '26 04:05

Marc Audet