how to center css navigation bar

2019-06-05 13:21发布

i am trying to center my css navigation bar but cant figure out why is not working, where am i doing wrong. i want it in the top center of the page. i tried margin:0 auto but it wont work here is my code:

<style>
    ul {
        list-style-type: none;
        padding: 0;
        overflow:hidden;
    }
    a:link,a:visited {
        margin:0 auto;
        display:block;
        width: 120px;
        font-weight:bold;
        color:#FFFFFF;
        text-align:center;
        padding:4px;
        text-decoration:none;
        text-transform:uppercase;
    }
    a:hover, a:active {
        background-color:#7A991A;
    }
    li {
        float: left;
    }
    #menu {
        background-color:#98bf21;
    }
</style>
<div id="menu">
        <header>
        <ul>
            <li><a href="Home.aspx">Home</a></li>
            <li><a href="News.aspx">News</a></li>
            <li><a href="Articles.aspx">Articles</a></li>
            <li><a href="Forum.aspx">Forum</a></li>
            <li><a href="Contact.aspx">Contact</a></li>
            <li><a href="About.aspx">About</a></li>
        </ul>
    </header>
    </div>

7条回答
smile是对你的礼貌
2楼-- · 2019-06-05 14:23

margin: 0 auto; only works on items that have defined widths. However, the way you currently have it written, each a tag is attempting to center, when you really want to center the ul. Here is a great way to center that when you don't know the width of your ul. Use these styles in your header, ul and li elements. Add styling to your a tags to suit.

header {
    float: left;
    width: 100%;
    overflow: hidden;
    position: relative;
}
ul {
    float: left;
    list-style: none;
    position: relative;
    left: 50%;
}
li {
    display: block;
    float: left;
    position: relative;
    right: 50%;
}

What's going on here is we're setting the header to full width, and then pushing the ul half way across the width of the browser. Then we push the li's back half the width of the ul, which now centers them on the page.

Here is a link with a very helpful tutorial about doing this very thing: http://matthewjamestaylor.com/blog/beautiful-css-centered-menus-no-hacks-full-cross-browser-support

Good luck!

查看更多
登录 后发表回答