Search code examples
csscenternavbar

CSS Issue Centering NavBar


So, essentially the last time I ever did any web-page development, there was only HTML, and I didn't have anymore than a basic understanding anyways. So now, I'm playing catch up and trying to learn CSS. My issue is a horizontal navbar, which doesn't stay perfectly centered. I've tried adjusting widths, and borders, and margins but I'm missing something.

With my current layout, there is a tad more whitespace on the left than the right, and I am stuck.

Here's the jsfiddle:

http://jsfiddle.net/PkvZ7/

CSS:

<!-- JASCO NAVBAR -->
ul
{
width:100%;
list-style-type: none;
margin-left:auto;
margin-right:auto;
padding:none;
overflow:hidden;
}

li
{
align:center;
width:20%;
margin:0;
padding:0;
display:inline-block;
list-style-type: none;
}
a:link,a:visited
{
display:block;
width:100%;
font-weight:bold;
font-size:20px;
color:#FFFFFF;
background-color:#FF6103;
text-align:center;
padding:5px;
text-decoration:none;
font-variant:small-caps;
}
a:hover,a:active
{
background-color:#000000;
color:#FF6103;
}

#container {
  width:100%
}

<!-- TOP CSS-->
.top {
position:absolute;
width:80%;
height:10%;
margin-left:auto;
margin-top:20px;
margin-right:auto;
color:#000000;
padding:0;
}

<!-- CONTENT CSS-->
.content {
position:absolute;
width 100%;
margin-left:10px;
margin-right:10px;
padding:3px;
color:#dddddd;
}

#img
{
}

<!-- TOP IMAGE CSS-->
img.center {
display:block;
margin-left:auto;
margin-right:auto;
}

HTML:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="jascostyle.css">
<title>Single"Frame" Test</title>
</head>

<body>
<div id="container">
  <center>
  <div class="top">
  <img class ="center" width="80%" height="5%" href="#temp" src="#temp" alt="JASCO ENERGY"/>
  <ul>
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  </ul>
  </div>


  <div  class="content">
  <h1>This is under construction!</h1>
  </div>
    </div>
  </body>
</html>

I appreciate any help/explanation on this matter.

Thanks.


Solution

  • You need a fixed width + margin-left:auto and margin-right:auto. You should not be using absolute positioning for your content - let it flow naturally.

    The <center> tag has been deprecated, so use the same technique for your outer "container" wrapper with a width of 960px;.

    ul {
        width:500px;
        list-style-type: none;
        margin-left:auto;
        margin-right:auto;
        padding:0;   
    }
    

    In general when using list-based menus, use float:left on your LI, use display:block on the A-tag and put all other styling on the A-tag, not the list itself.

    See my tutorial: I Love Lists.