Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I center floated list items?

Tags:

html

css

center

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>
like image 381
Aaron Benjamin Avatar asked Jun 24 '13 00:06

Aaron Benjamin


People also ask

How do you center a floating element?

The CSS float property is used to set or return the horizontal alignment of elements. But this property allows an element to float only right or left side of the parent body with rest of the elements wrapped around it. There is no way to float center in CSS layout.

How do I make a list centered?

To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element. Now, add the style to the div class and use the text-align property with center as its value. See the below example.

How do I center a list item in CSS?

To center one box inside another we make the containing box a flex container. Then set align-items to center to perform centering on the block axis, and justify-content to center to perform centering on the inline axis.

How do you center a floated image in HTML?

An <img> element is an inline element (display value of inline-block ). It can be easily centered by adding the text-align: center; CSS property to the parent element that contains it. To center an image using text-align: center; you must place the <img> inside of a block-level element such as a div .


2 Answers

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/

like image 173
John Avatar answered Sep 19 '22 14:09

John


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

like image 26
Cynthia Avatar answered Sep 23 '22 14:09

Cynthia