I want to have my navigation bar in the middle of the page but I don't know what to do. Here is my code.
CSS
ul {
list-style-type:none;
margin:0;
padding:0;
overflow:hidden;
}
li {
float:left;
}
a {
display:block;
width:80px;
background-color:#000000
}
HTML
<ul>
<li><a href="http://kevril.site40.net/">Home</a></li>
<li><a href="http://www.youtube.com/user/SuperKevril">Youtube</a></li>
</ul>
Centering block level elements is easy, just define a width
and set margin:0 auto;
, but what if you don’t know that fixed width? You could use text-align:center;
, but that won’t work on width:100%
block-level elements either… that will only work on text-level elements.
Defining explicit width
and height
should always be avoided wherever possible, as doing so will make the document a lot less future-proof, flexible and extensible. Suppose you have four items in your navigation menu. You can work out the width
of these and use margin:0 auto;
to center them. Adding a fifth will increase the width, meaning you’d need to alter the CSS, too. This is far from ideal, and more so with a CMS to power the site (a client can add pages, but perhaps can’t edit CSS).
However, there is a way to have a centered horizontal navigation without knowing an explicit width, and without adding CSS. It’s also remarkably easy. Try this:
HTML:
<ul class="nav">
<li><a href="/">Home</a></li>
<li><a href="/about/">About</a></li>
<li><a href="/work/">Work</a></li>
<li><a href="/clients/">Clients</a></li>
<li><a href="/contact/">Contact</a></li>
</ul>
CSS:
.nav{
border:1px solid #ccc;
border-width:1px 0;
list-style:none;
margin:0;
padding:0;
text-align:center;
}
.nav li{
display:inline;
}
.nav a{
display:inline-block;
padding:10px;
}