CSS center ul list inside a 100% width div

谁说胖子不能爱 提交于 2019-12-08 10:15:49

问题


I feel as if I have tried everything from text-align center to margin:0 auto with a position relative and width of 100%, but they didn't work, I am trying to center my UL inside the div...

Here is my code

<style type="text/css">

.header {
  height: 40px;
  background: #000;
  width: 100%;
}

.header ul {
  list-style-type: none;
}

.header li {
  float: left;
  line-height: 40px;
}

.header li a {
  color: #FFF;
  padding: 0 18px;
  height: 40px;
}

</style>
<div class="header">
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Gallery</a></li>
    <li><a href="#">Services</a></li>
    <li><a href="#">Rates</a></li>
    <li><a href="#">Reviews</a></li>
    <li><a href="#">FAQ</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</div>

回答1:


This works without having to define a set width.

ul {
    display: table;
    margin: 0 auto;
}

If you want to get rid of the left-side padding, thus genuinely centering the list, add:

padding-left: 0;



回答2:


This should fix it for you.

ul {
    display: inline-block;
    margin: 0 auto;
}

If that doesn't work for you then give the UL a set width i.e.

ul {
    width: 300px;
    margin: 0 auto;
}


来源:https://stackoverflow.com/questions/14943907/css-center-ul-list-inside-a-100-width-div

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