Search code examples
cssheaderalignmentcenter

Vertical and Horizontal center align within a div


I need some help here. I been trying to get it right for hours and i can't find an efficient solution.

<div id="Header">
<img src='http://3.bp.blogspot.com/-rN0cMMTn_Mw/ToQ6VTghSOI/AAAAAAAAAfs/xl1XMFyn7Jo/s640/18_5_orig.jpg'
/>
 <h1>siajdasdasdasd</h1>

<p>sdhaosidasdas</p>

Example of what im trying to do

i want to have a liquid header with an image aligned to the left and a title aligned to the center, but both of em have to align to the middle of the height, no mather if i increase img /div's height


Solution

  • For modern browsers you can do it via display:table, table-row table cell:

    Modify your html like this:

    <div id="Header" class="table">
        <div class="row">
            <div class="cell">
                <img src='http://3.bp.blogspot.com/-rN0cMMTn_Mw/ToQ6VTghSOI/AAAAAAAAAfs/xl1XMFyn7Jo/s640/18_5_orig.jpg'/>
            </div>
            <div class="cell main">
                 <h1>siajdasdasdasd</h1>
                 <p>sdhaosidasdas</p>
            </div>
        </div>
    </div>
    
    #Header {
        background: #DBE6EC;
        border-bottom: 1px solid #595959;
        position:relative;
        padding:15px;
        -moz-box-sizing: border-box; 
        -webkit-box-sizing: border-box; 
        box-sizing: border-box; 
    }
    
    .table {
        display:table;
        width:100%;
    }
    
    .row {
        display:table-row;
    }
    
    .cell {
        display:table-cell;
        vertical-align:middle;
    }
    
    .cell.main {
        width:100%;
    }
    

    The updated fiddle is here. This solution won't work in ie7. There is a older workaround for vertical align middle, if you have to support ie7.