How do I center floated list items?

旧街凉风 提交于 2019-12-09 11:29:25

问题


I have list items for my site nav that I need to center. I'm floating so that I can have padding on the list items...setting them to inline seems to eliminate top and bottom padding.

<style type="text/css">

   #nav {
       width:100%;
   }

   #nav ul {
       margin-right: auto;
       margin-left: auto;
   }

   #nav ul li {
      float: left;
      background-color: #333;
      color: #fff;
      padding: 15px;
      margin: 10px;
   }

</style>

<div id='nav'>

   <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
      <li>Item 4</li>
  </ul>

</div>

回答1:


By making the items display inline you can then align them as text. Setting the line height fixed wrapping issue.

 #nav{
        text-align: center;
        line-height:30px;

    }

    #nav li {
        list-style:none;
        margin: 0 5px;
        display:inline;
        border:gray solid 1px;
    }

Working demo can be seen here: http://jsfiddle.net/AqRJA/1/




回答2:


Try changing your CSS to:

#nav ul{

margin-right:auto;
margin-left:auto;
text-align:center;

}

#nav ul li{
display:inline;
background-color:#333;
color:#fff;
padding:15px;
margin:10px;

}

Cheers,

Cynthia




回答3:


give width to ul

replace your class with this one

   #nav ul {
       margin-right: auto;
       margin-left: auto;
       width:400px;
   }



回答4:


I've been through the same thing sooooo many times.

You can't center anything with % layout, you have to be specific in pixels or ems.

So I changed your code to give the div a specific width and then centered it.

`<div class="centerme">
      <!--put your stuff here-->
   </div>`   

Here's the jsfiddle:

http://jsfiddle.net/EqNtH/



来源:https://stackoverflow.com/questions/17266618/how-do-i-center-floated-list-items

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