简体   繁体   中英

How do I center floated list items?

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>

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/

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

give width to ul

replace your class with this one

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM