How do I center the navigation menu?

2020-08-07 17:15发布

问题:

I am using the following codes to create a layout, the issue is, the navigation menu won't center, the text centers, but the rest of the navigation bar doesn't.

Here is my HTML:

<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <title>Test</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>
    <div id="container">
    <h1>Test</h1>


    <ul id="navigation">
        <li><a href="#">Home</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Projects</a></li>
        <li><a href="#">Contact</a></li>
    </ul>


    <div id="content">
    </div>

    <div id="footer">
        <p>Test</p>
    </div>

    </div>
</body>

</html>

And here is my CSS:

/***** Body *****/
body {
    font-family: arial, helvetica;
    text-align:center;
}

div#container {
}

/***** Navigation Menu *****/

ul#navigation {
    margin: 20px;
    padding: 0;
    list-style: none;
    width: 525px;
}

ul#navigation li {
    display: inline;
}

ul#navigation a {
    text-decoration:none;
    padding: 5px 0;
    width: 100px;
    background: #485e49;
    color: #eee;
    float: left;
    text-align:center;
}

ul#navigation a:hover {
    background: #FF00FF;
    text-align:left;
}

ul#navigation a:active {
    text-align:right;
}

回答1:

Change your ul#navigation to

ul#navigation {
    padding: 0;
    list-style: none;
    width:400px;
    margin:0 auto;    
}

Example: http://jsfiddle.net/jasongennaro/3WS7B/

What happened is your width was off. Once that was fixed to 400px, applying margin:0 auto worked.



回答2:

You can add this to the ul#navigation css to center it:

margin:0 auto 0 auto;

Alternatively:

margin-left:auto;
margin-right:auto;