Search code examples
htmlcsspositioncenter

HTML | Center menubar on screen


need some help. I'm just learning HTML and have been looking at how to do menus today, whilst doing so I have ran into a problem.

I can't seem to figure out how to center the menu on screen.

This is what I have so far;

<div id="navMenu">
    <ul>
        <li><a href="#">Home</a></li>

        <li><a href="#">WWW.</a>
        <ul>
            <li><a href="#">Through the years</a></li>
        </ul></li>

        <li><a href="#">Browsers</a>
        <ul>
            <li><a href="#">IE</a></li>
            <li><a href="#">Firefox</a></li>
            <li><a href="#">Chrome</a></li>
        </ul></li>

        <li><a href="#">CSS</a>
        <ul>
            <li><a href="#">CSS 2.1</a></li>
            <li><a href="#">CSS 3</a></li>
        </ul></li>

        <li><a href="#">Scripting</a>
        <ul>
            <li><a href="#">JavaScripts</a></li>
            <li><a href="#">jQuery</a></li>
        </ul></li>

    </ul>
</div>

Current CSS;

#navMenu{
    margin:0;
    padding:0;
}
#navMenu ul{
    margin:0;
    padding:0;
    line-height:30px;
}
#navMenu li{
    margin:0;
    padding:0;
    list-style:none;
    float: left;
    position: relative;

    background-color: #999;
    border-radius: 5px;
}
#navMenu ul li a{
    text-align: center;
    text-decoration:none;
    height:30px;
    width:150px;
    display:block;
    color: #FFF;
    border: 1px solid #FFF;
    text-shadow: 1px 1px 1px #000;
}
#navMenu ul ul{
    position:absolute;
    visibility:hidden;
    top:32px;
}
#navMenu ul li:hover ul{
    visibility:visible;
}
#navMenu li:hover{
    background-color: #09F;
}
#navMenu ul li:hover ul li a:hover{
    background-color: #CCC;
    color: #000;
}
#navMenu a:hover{
    color:#000;
}

The above produces this .... http://gyazo.com/55cf62d121ef16eb1248e5246d0accae

Anyway to get the menu bar in the center of the screen.

SIDE NOTE:: Any spoilers tags on this site?


Solution

  • Try using display: inline-block and text-align: center.

    Set display: inline-block for the <ul> and text-align: center for the container #navMenu. Set text-align: left for #navMenu li to fix the submenus.

    Also

    Example

    #navMenu{
        margin:0;
        padding:0;
        text-align: center;
    }
    #navMenu ul{
        margin:0;
        padding:0;
        line-height:30px;
        display: inline-block;
    }
    #navMenu li{
        margin:0;
        padding:0;
        text-align: left;
        float: left;
        list-style:none;
        position: relative;
        background-color: #999;
        border-radius: 5px;
    }