No replies
gautamz07
gautamz07's picture
Offline
Enthusiast
Last seen: 3 years 18 weeks ago
Timezone: GMT+5.5
Joined: 2014-04-24
Posts: 265
Points: 403

this is what somebody has to say about centering a ul in a div :

so assume the HTML to be something like this :

  <div id="headermenu">
      <ul>
        <li>Yo Yo honey !!</li>
        <li>Yo Yo honey !!</li>
        <li>Yo Yo honey !!</li>
        <li>Yo Yo honey !!</li>
        <li>Yo Yo honey !!</li>
        <li>Yo Yo honey !!</li>
        <li>Yo Yo honey !!</li>
      </ul>
  </div>

ANSWER STARTS FROM HERE :

Solution 1: max-width: 660px; and margin: 0 auto; (IE7+)

You can center a block-level element by assigning a fixed width and margin-right and -left set to auto.

#headermenu ul {
    max-width: 660px; /* for  below IE7 use `width: 660px;` */
    margin: 0 auto;
}

Solution 2: display: inline-block; and text-align: center; (IE8+)

Centering an element just like you would do with regular text is possible as well. Downside: You need to assign values to both a container and the element itself.

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

This solution is better suited if you have a different number of menu items and can't use a fixed width.

Solution 3: display: table; and margin: 0 auto; (IE8+)

Just like solution 1, you use auto values for right and left margins, but don't assign a width. If you don't need to support IE7 and below, this is better suited.

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

Solution 4: transform: translatex(-50%); and left: 50%; (IE9+)

This is similar to the quirky centering method which uses absolute positioning and negative margins.

#headermenu ul {
    position: relative;
 
    /* This works with `top: 50%;`... */
    left: 0;
 
    /* ...and `translate(-50%, -50%)` as well. */
    transform: translatex(-50%);
}

Check caniuse.com for the browser support, because you're going to need prefixing here.

ANSWER ENDS HERE.

in the above example assume #headermenu to be a div .

now i am using chrome 39.0.2171.95.

and text-align-center(on the main div) just works fine for me.

so are the above hacks really needed ??

the thread can be found here: link

Thanks.

gautam.