I\'m not able to align a menu, contained within a ul
, to the horizontal center of its container. how to do that?
See a live demo of the menu on jsFiddle.
There is a very neath, fully cross-browser and dynamic 'trick' to achieve this, as long as the menu stays on one line. It is very well explained here: http://matthewjamestaylor.com/blog/beautiful-css-centered-menus-no-hacks-full-cross-browser-support
The inline-block often suggested for this problem is not very well supported in legacy browsers in my experience. To be honest, I never use it. I always go for the clever method that Matthew James Taylor describes.
Edit: As requested I will briefly describe the technique. Your html should look like a normal list of links, with an extra wrapping div around it. Something like this:
<div class="menu-wrapper">
<ul>
<li><a ...>link</a></li>
<li><a ...>link</a></li>
<li><a ...>link</a></li>
</ul>
</div>
Now the rest is css work. The steps are as follows:
ul
and the li
to the left and don't give them any width to make them adjust to their content.ul
a position: relative
of left: 50%
. This will make it's left edge move to the center of it's parent, and this means the center of the viewport.li
a position: relative
of left: -50%
. This will make them move past the left edge of the parent ul
and makes the center of the list of li
's line up with the left edge of the parent ul
. Since we made that edge the center of our viewport in the previous step, the menu is now effectively centered.As I said before, all credits to Matthew James Taylor, and definitly check out his thorough explanation. The drawings he made make it much easier to understand.
edit
As requested I set up a little fiddle to demonstrate the technique:
http://jsfiddle.net/fDmCQ/
You can address the ul
element as an inline-level element within the page flow, while retaining its block-level characteristics (using the inline-block
display value) — after applying this, it can be simply aligned within its container like any inline-level element, using text-align
.
To implement this, add the following rules:
#container {
text-align: center;
}
ul {
display: inline-block;
}
Here's the updated demo.
Disclaimer: Support for inline-block
is somewhat limited, see the compatibility table on caniuse.com.
Change the margin on the <ul>
to 0 auto
and give it a width (~575px or larger).
jsFiddle example
ul {
font-family: Arial, Verdana;
font-size: 14px;
margin: 0 auto;
padding: 0;
width:600px;
list-style: none;
text-align: center;
}