Center navigation bar with CSS

2019-03-04 10:39发布

问题:

I am trying to center my nav bar. I checked my sites but nothing works and I'm completely stumped as to why it won't center, here is my navigation bar HTML that I want to center:

<div class='nav'>
<ul class='menu' id='menu'>
<li><a expr:href='data:blog.homepageUrl'>home</a></li>
<li><a class='drop-ctg' href='#'>PORTFOLIO</a>
   <ul>
     <li><a href='http://effectsforshare.blogspot.com/p/trailer.html'>TRAILER</a></li>
     <li><a href='http://effectsforshare.blogspot.com/p/motion-graphics.html'>MOTION GRAPHICS</a></li>
     <li><a href='http://effectsforshare.blogspot.com/p/trapcode-particular.html'>TRAPCODE PARTICULAR</a></li>

   </ul>
</li>
<li><a href='http://effectsforshare.blogspot.com/'>TEMPLATES</a></li>
<li><a href='http://effectsforshare.blogspot.com/p/my-blog.html'>MY BLOG</a></li>
<li><a href='http://effectsforshare.blogspot.com/p/contact-me.html'>CONTACT ME</a></li>


</ul>
</div>

and here is the CSS

*{
  margin:0;
  padding:0;
  outline:0;
}
.nav {
  width:950px;
  height:auto;
  border-bottom:1px solid #eee;
  margin:10px auto 5px;
  display:inline-block;
}
.menu {
  width:auto;
  list-style:none;
  font:$pagenavifont;
  text-align:center;
  margin:0 auto;
}
.menu a {
  float:left;
  color:#999;
  text-decoration:none;
  text-transform:uppercase;
  width:auto;
  line-height:36px;
  padding:0 20px;
}
.menu a:hover,li.menuhover a{
  color:#111;
}
.menu li {
  position:relative;
  float:left;
  width:auto;
}
.menu li:last-child {
  background:none;
}
.menu ul{
  display:none;
  position:absolute;
  top:36px;
  left:0;
  background:#fbfbfb;
  display:none;
  list-style:none;
}
.menu ul li{
  float:none;
  border-top:1px solid #e3e3e3;
  border-right:1px solid #e3e3e3;
  border-left:1px solid #e3e3e3;
  width:auto;
  background:none;
}
.menu ul li:last-child {
  border-bottom:1px solid #e3e3e3
}
.menu ul li a{
  float:none;
  display:block;
  background:none;
  line-height:36px;
  min-width:137px;
  width:auto;
  text-align:left;
  padding-left:10px;
  color:#444;
}

.menu ul li a:hover{
  background:#fdfdfd;
  color:#777;
}

I would give you a link to the page but it's being done in Dreamweaver and is not up yet. The logobar.jpg is the logo for the webpage. I love how it looks, but it needs to be centered and not be cut off or taken to the next line when I shrink my screensize.

I tried each of float: right, float: left, and float: none on almost all of the classes; text-align: center on each class on the html side; I have tried align=center on each class; display: inline, inline-block on ul and li classes.

Thank you for your help!

回答1:

On your .menu class, you do have text-align:center set. We can certainly use that to center the child nodes.

So within your .menu li css property, add display:inline-block and remove the floats. This will center your list items.

See the fiddle: http://jsfiddle.net/RGREA/



回答2:

<style>
div.nav{margin: 3px auto;}
</style>