简体   繁体   中英

I'm having trouble center-aligning a div

So I have a header for a website like this:

http://i.stack.imgur.com/k4hjp.png

And I'm trying to align the navigation menu to the center. The navigation div is inside the center columnn (in black) and the CSS for it is:

.nav {
    text-align: center;
    margin: 0 auto;
    position: relative;
    top: 287px;
    width: 100%;
    height: 70px;
    z-index: 100;
}

At the moment, each button in the navigation is yet another div. If someone has suggestions about how to approach it without having so many divs I would appreciate it, but anyway the code for the buttons is:

.button {
    margin-left: 10px;
    float: left;
    position: relative;
    text-align: center;
    line-height: 40px;
    width: 135px;
    height: 40px;
    background: #aa0000;
    color: #fff;
    font-weight: bold;

}

I have even tried setting text-align in body to center, but it won't work. How can I center align this menu?

Right now it is the "float:left" on your divs that makes them stay left aligned. Replace that float with "display:inline-block;" and you are fine. And, if you don't want to use those divs, you could try to go with a list. A common practice for menus is something like this:

<ul>
  <li>Menu item a</li>
  <li>Menu item b</li>
</ul> 

Styles:

.centerDiv { 
            width: 60%; 
            height:70px; 
            margin: 0 auto; 
            text-align: center;
            top: 287px;
            z-index: 100;
        } 

        .buttonDiv { 
            width: 10%; 
            height:40px; 
            background-color:#aa0000; 
            float:left; 
            margin-left: 10px;
            position: relative;
            text-align: center;
            line-height: 40px;
            color: #fff;
            font-weight: bold;
        } 

Markup:

<div class="centerDiv">
            <div class="buttonDiv">Button 1</div>
            <div class="buttonDiv">Button 2</div>
            <div class="buttonDiv">Button 3</div>
            <div class="buttonDiv">Button 4</div>
            <div class="buttonDiv">Button 5</div>
            <div class="buttonDiv">Button 6</div>
        </div>

Sorry for the self-answer, but none of the answers solved the problem exactly. Apparently the nav container width being set to 100% prevented any centering. After setting it to a static value, I was able to align normally. Thanks everyone for the help!

Use <a> instead of divs you can make it look attractive like

a{
display:block;
background-color:red;
width:100px;
}

then use text-align:center it will align

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM