8

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

hello
  • 1,168
  • 4
  • 24
  • 59
  • add `position: absolute` to `.homeImageText` and `position: relative` to `header` – Mathias Mar 31 '14 at 14:25
  • @Mathias That did not solve the issue I have. – hello Mar 31 '14 at 14:25
  • Note that this doesnt center the div itself, it makes it the same size as the parent – SW4 Mar 31 '14 at 14:30
  • possible duplicate of [What's The Best Way of Centering a Div Vertically with CSS](http://stackoverflow.com/questions/396145/whats-the-best-way-of-centering-a-div-vertically-with-css) – strah Mar 31 '14 at 14:30
  • [How's this?](http://jsfiddle.net/peteng/sa3Mk/3/) – Pete Mar 31 '14 at 14:31

1 Answers1

11

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;
}
SW4
  • 69,876
  • 20
  • 132
  • 137