Search code examples
htmlcsspositioncentering

Vertical and Horizontal centering a div inside another


I am trying to center a div inside another div. I have tried the following HTML and CSS

HTML

<div class="header">
 <div class="homeImageText">
    <h1>Document Preparation Like Never Before</h1>
    </div><!--homeImagetext end-->
</div>

CSS

.homeImageText {
left:0; right:0;
top:0; bottom:0;
margin:auto;
max-width:100%;
max-height:100%;
}

header{
background: url(../images/header1.png) center center no-repeat; ;
height: 600px;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

Live jsfiddle


Solution

  • Demo Fiddle

    For vertical centering, make the wrapping div set to display-table and the child to display:table-cell with vertical-align:middle. Horizontal centering can then simply be accomplished with text-align:center;

    Try the CSS:

    .header {
        height: 600px;
        display:table;
        width:100%;
    }
    .homeImageText {
        height:100%;
        display:table-cell;
        vertical-align:middle;
        text-align:center;
    }