My code is simple, I just want a navigation bar that shows it's links horizontally. Should be very easy, but I've never been able to do it. Examples found online go like this:

<!-- Navigator -->
    <div id="nav">
        <ul>
            <li><a href="#">Anchor 1</a></li>
            <li><a href="#">Anchor 2</a></li>
            <li><a href="#">Anchor 3</a></li>
        </ul>
    </div>

and the CSS:

/* So it's cantered on top */
#nav {
margin:0 50%; 
position:fixed;

}

#nav ul {
list-style-type:none;
margin:0;
padding:0;
position: absolute;
}   

#nav ul li {
float:left;
}   

As far as I know, this SHOULD work, can someone please exlain me what's wrong? Removing the position:fixed of #nav turns it horizontal, but it wont stick to the top of my viewport.

有帮助吗?

解决方案

You just over complicated things. Get rid of all the positions you have used because you do not need them at all. I just mocked something up on codepen for you to have a look: http://codepen.io/nighrage/pen/mhgze. The following css is all you need and the menu will be responsive to a certain extend. Let me know if you want to do something in addition to how it is displayed.

#nav ul {
list-style-type:none;
margin:0;
padding:0;
width:100%;
float:left;
text-align:center;
}   

#nav ul li {
display:inline-block;
padding: 0 10px;
}  

其他提示

Try removing the position:absolute from the ul. I do not think it's needed to accomplish your goal.

#nav ul {
list-style-type:none;
margin:0;
padding:0;
}   

It's not working because of two reasons : 1. The margin 3. I think the list items are being set to absolute (inherited). Set it to static.

Here's a fiddle : http://jsfiddle.net/txDSa/

#nav {
position:fixed;
}

#nav ul {
list-style-type:none;
margin:0 !important;
padding:0;
position: static;
}   

#nav ul li {
margin:0 ;
float:left;
}  

you could remove the the position absolute http://jsfiddle.net/gdiamond/Jn9P6/

#nav {
margin:0 auto;
width:300px;
}

#nav ul {
list-style-type:none;
margin:0;
padding:0;
}   

#nav ul li {
float:left;
padding-left: 12px;
}
/* So it's cantered on top */
#nav {
text-align:center;
}

#nav ul {
display:inline;
}   

#nav ul li {
display:inline-block;
padding:10px;
}   

Jsfiddle here: http://jsfiddle.net/4EJHF/

Basically you want the text aligned to center on your nav element. Then your unordered list should be displayed inline. Finally, your list elements shoud be displayed inline-block.

There is another method with two floats, but you would need to manually center the navigation:

#nav ul {
float:left;
list-style-type:none;
}   

#nav ul li {
float:left;
padding:10px;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top