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.
<li><a href="aboutus.php">AboutUs</a>
<ul class="sub">
<li><a href="aboutsquare.php">About Square Innovations</a></li>
<li><a href="ourvision.php">Our Vision</a></li>
<li><a href="ourmission.php">Our Mission</a></li>
<li><a href="trainerprofiles.php">Trainer Profiles</a></li>
<li><a href="funclass.php">Fun In Our ClassRooms</a></li>
</ul>
</li>
Change the margin on the
<ul>
to0 auto
and give it a width (~575px or larger).jsFiddle example
You can address the
ul
element as an inline-level element within the page flow, while retaining its block-level characteristics (using theinline-block
display value) — after applying this, it can be simply aligned within its container like any inline-level element, usingtext-align
.To implement this, add the following rules:
Here's the updated demo.
Reference
display
on Mozilla Developer NetworkDisclaimer: Support for
inline-block
is somewhat limited, see the compatibility table on caniuse.com.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:
Now the rest is css work. The steps are as follows:
ul
and theli
to the left and don't give them any width to make them adjust to their content.ul
aposition: relative
ofleft: 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
aposition: relative
ofleft: -50%
. This will make them move past the left edge of the parentul
and makes the center of the list ofli
's line up with the left edge of the parentul
. 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/