HeroicNate
HeroicNate

Reputation:

Centering a ul with floats inside a div

I'm trying to center this bottom nav on a test site:

http://heroicdreams.com/kktest/

The ul li uses float:left; which is what I think is making it stay stuck to the left. I'm trying to figure out how to get it to be centered.

To get the links displayed horizontally I needed to float them left, but now I can't get the whole nav to be centered. Is there a way?

Upvotes: 5

Views: 16127

Answers (6)

Phil LaNasa
Phil LaNasa

Reputation: 3035

Hmm, I think the KISS rule applies here:

ul { text-align: center; }
ul li { display: inline-block; }

Upvotes: 0

Emily
Emily

Reputation: 10088

In order for margin:0 auto to work, you need to set a width on your ul and remove the display:inline:

#footerLinks ul {
  list-style:none;
  margin:0 auto;
  padding:0;
  width:400px;
}

Upvotes: 0

Dashrath
Dashrath

Reputation: 2189

  1. Add style="text-align: center;" to the parent div of the ul.
  2. Add style=" display:inline-table;" to the ul.

Upvotes: 1

Gurita Radu
Gurita Radu

Reputation: 11

Here is how I solved it, and is for dynamically generated menus also.

Assume this is the dynamically generated menu:

<div id="menu">
   <ul>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
   </ul>
</div>

and this is the CSS:

.menu {
    width:300px;
    text-align: center; /*Set a width and text-align on the main div*/
}

.menu ul{
    margin:0;
    padding:0;
    display:inline-block;
    list-style: none;   /*Set display to inline-block to the ul*/
}

.menu ul li {
    float: left;
    margin-right: 1.3em; /*this is the usual*/
    padding: 0;
}

Now, for the list to be centered you need to add an empty paragraph to clear the float. You can do it manually if the menu is static or using jQuery like this:

$(document).ready(function() {
    $("<p class='clear'></p>").insertAfter('.menu-header ul li:last-child');
})

and the CSS of the .clear paragraph will be:

p.clear{
    clear:both;
    margin:0;
    padding:0;
    height: 0;
    width: 0;
}

and that's it!

Upvotes: 1

jkelley
jkelley

Reputation: 2640

often using:

.divStyle {
    text-align: center;
}
ul.styleName {
    margin: 0 auto; 
    text-align: left;
}

will do the trick.

Applying an "auto" margin to the left and right of the ul like this will cause it to center itself in the div whenever the div has centered text. This is how many websites center the div that serves as the main content of their page.

Upvotes: 7

user142019
user142019

Reputation:

Either CSS:

margin: 0px auto;

or

/*on the nav's parent*/
text-align: center;

/*on the nav*/
text-align: left;

Upvotes: 0

Related Questions