Center unordered list in DIV

感情迁移 提交于 2019-12-03 00:36:33

Your HTML is incorrect. The <a> tags should be inside the <li> tags. To make the list items be inline, set float: left on them, and overflow: hidden to the <ul> so it fits its children. Remove the float on .nav-container, its unecessary. Take a look at this codepen.
And the nav moves when you change its width because it you centered the wrapper but not the nav itself. You can remove width and margin: 0 auto and try:

.nav-container {
    text-align: center;
}
.nav-container ul {
    display: inline-block;
}

The problem was that you were assigning fixed widths to the li's of 150px.. Instead you should have assign the width to 33% and also assign the width of the ul to 100%, this way, no matter what size the div is, the three li's will be centered perfectly :)

Here's the updated JSFIDDLE

.nav-container ul {
  padding: 0px;
  list-style:none;
  float:left;
  width: 100%
}
.nav-container ul li {
  display: inline;
}
.nav-container ul a {
  text-decoration:none;
  padding:5px 0;
  width:33%;
  color: #ffffff;
  background: #317b31;
  float:left;
  border-left: 1px solid #fff;
  text-align:center;
}

The following solution is a bit refined:

   html * {
       font-family: Verdana, Geneva, sans-serif;
   }
   body {
       padding:0px;
       margin:0px;
   }
   .nav-container {
       width:460px;
       margin: 0 auto;
   }
   .nav-container ul {
       padding: 0px;
       list-style:none;
       float:left;
   }
   .nav-container ul li {
       display: inline;
   }
   .nav-container ul a {
       text-decoration:none;
       padding:5px 0;
       width:150px;
       color: #ffffff;
       background: #317b31;
       float:left;
       border-left: 1px solid #fff;
       text-align:center;
   }
   .nav-container ul a:hover {
       background: #92e792;
       color: black;
   }
   #add-form .add-button, #tutor-list .tutor-button, #admin .admin-button {
       color: #ffffff;
       background: #12b812;
   }


<div id="header">
    <center>
         <h2>OMS Tutoring Database</h2>
    </center>
</div>
<div class="nav-container">
    <ul>
         <li><a class="tutor-button" href="tutoring.php">Tutoring List</a></li>
         <li><a class="add-button" href="addform.php">Add Students</a>
         <li><a class="admin-button" href="admin.php">Admin</a></li>
    </ul>
</div>

Try it at: http://jsfiddle.net/hg9qvL70/2/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!