Search code examples
htmlcssalignmenthtml-lists

How to horizontally align a ul element to center


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>

Solution

  • 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.

    Reference


    Disclaimer: Support for inline-block is somewhat limited nope! it's actually very wide by now, see the compatibility table on caniuse.com.