Search code examples
htmlcssalignmentvertical-alignment

I am having difficulty vertically aligning a nav element inside its parent div.


Everything I try creates a new problem. It often gets pushed out when I use the line-height: property as well. How can I successfully center this element?

CSS:

#parent {
    background: #000; 
    background: rgba(0,0,0,0.50);
    width: 100%;
    height: 70px;
    position: fixed ;
    z-index: 9999;
}

#child {
    display: inline;
    text-align: center;
    float: right;
    margin-right: 30px; 
}

ul.menu2 {
    cursor: default;
    border-bottom: 0;
    margin-bottom: 0;
}

ul.menu2 li {
    display: inline-block;
    line-height: 1em;
    padding: 0 0 0 0.5em;
    margin: 0 0 0 0.5em;
}

HTML:

<div id="parent">
        <nav id="child" role="navigation">
            <ul class="menu2">
                <li><a href="#home" rel="home_link" class="scrolly">Home</a></li>
                <li><a href="#banner" rel="about_link" class="scrolly scrolly-centered">About</a></li>
                <li><a href="#first" rel="events_link" class="scrolly">Shows</a></li>
                <li><a href="#" rel="artists_link">Music</a></li>
                <li><a href="#" rel="contact_link">Contact</a></li>
            </ul>
        </nav>  
    </div>

Solution

  • If you want to use line-height and inline-block to vertical-align, you should not use float. text-align will do.

    You can set height of nav with line-height and set ul on the middle of it.

    DEMO

    #parent {
        background: #000; 
        background: rgba(0,0,0,0.50);
        width: 100%;
        top:0;
        left:0;
        text-align:right;/* ul will go right */
        line-height: 70px;/* as ul should stand on one line, it is enought to size height of nav */
        position: fixed ;
        z-index: 1;/* 1 should do it */
    }
    
    #child {
        display: inline-block;/* make me an inline-box, now i can hold anything, block, float, multi-lines, .. */
        text-align: center;/* reset text-align */
        margin-right: 30px; /* or padding-right, whatever */
        vertical-align:middle;/* set me on middle of line-height */
    }
    
    ul.menu2 {
        cursor: default;
        border : 0;
        margin : 0;/* usefull reset i believe :) */
        line-height:1.2em; /* reset line-height here to regular values :) in case text , inline-boxes split on 2 or more lines*/
    }
    
    ul.menu2 li {
        display: inline-block;
        padding: 0 0 0 0.5em;
        margin: 0 0 0 0.5em;
    }