Search code examples
csscenterpaddingvertical-alignmentnavigationbar

How can I vertically center text in a ul navigation-bar without these multiple CSS conflicts?


I have made a functional CSS navigation-bar, except for some fugly CSS side-effects --

I am trying to vertically center the text in each list block, and vertical-align: middle was not working. Instead, I am using padding-top: 13px, but this renders the padded area without the background-color of the rest of the list element, and the display: inline block styling of the link does not extend to the padded area either! (a:hover is affecting only the area below the padding)

So how can I vertically center text in list elements without these CSS problems?

Here is the relevant CSS:

/* header section */
#header
{
    padding-left: 115px;
    margin-bottom: 10px;
}
    #main-menu
    {
        list-style-type: none;
    }
    #main-menu li
    {
        border: 1px solid black;
        text-align: center;
        padding-top: 13px;

        color: #666;
        font-family: "Lucida Console";
        font-variant: small-caps;
        letter-spacing: 2px;

        /* for  block layout */
            display: -moz-inline-box; /* for firefox */
            display: inline-block;

        width: 153px;
        height: 32px;
    }
    #main-menu a:link, a:visited
    {
        display: -moz-inline-box; /* for firefox */
        display: inline-block;

        width: 100%;
        height: 100%;
        background-color: #eee;
    }
    #main-menu a:hover, a:active
    {
        background-color: #bbb;
    }<br /><br />

...and here is the relevant HTML:

        <!-- header section -->
        <div id = "header">
            <ul id = "main-menu">
                <!-- no spaces between list elements when all on the same line! -->
                <li><a href = "home.html" title = "home">home</a></li><li><a href = "about.html" title = "about">about</a></li><li><a href = "cart.html" title = "shopping cart">cart</a></li><li><a href = "login.html" title = "log in">login</a></li><li><a href = "createAccount.html" title = "create a new account">sign up</a></li>
            </ul>

        </div> <!-- end of header section -->

Solution

  • Things that I changed:

    • Changed the link to display as a block element.
    • Removed the padding at the top of the li elements.
    • Added that padding height to the height of the li elements.
    • Set the line-height to the height of the li elements.
    • Some formatting

    http://jsfiddle.net/gtr053/7yrX7/