Si8 Si8 - 3 days ago 6
CSS Question

align UL to center of DIV

I am trying to center

<ul>
inside
<div>
but I tried the


text-align: center


and


left:50%


not working...

My CSS is:

#headermenu {
clear: both;
width: 800px;
height: 70px;
margin-bottom: 10px;
text-align: center;
}

#headermenu ul {
padding: 0 0 0 20px;
margin: 0;
list-style: none;
}

#headermenu ul li {
margin: 0;
padding: 0;
}


But I want it to center the menu on the page.

Answer

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 {
    position: relative;
}

#headermenu ul {
    position: absolute;

    /* This works with `top: 50%;`... */
    left: 50%;

    /* ...and `translate(-50%, -50%)` as well. */
    transform: translatex(-50%);
}

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

Lastly, a demo that summarizes all of the 4 solutions above.


For using Flexible Box Layout Module, refer to this answer: Horizontally center a div in a div

Comments