0

How do I horizontally and vertically center a dynamic div in a div with 100% viewport size?

html

<div class="outer-div">
    <div class="inner-div"></div>
</div>

css

html, body {
    height: 100%;
}

.outer-div {
    height: 100%;
    width: 100%;
    background-color: #f3f3f3;
}

.inner-div {
    width: 80%;
    height: 80%;
    background-color: #ccc;
}
anna
  • 53
  • 5
  • 1
    http://css-tricks.com/centering-in-the-unknown/ http://www.smashingmagazine.com/2013/08/09/absolute-horizontal-vertical-centering-css/ – Dominic Aug 05 '14 at 10:04

2 Answers2

3

Demo

css

html, body {
    height: 100%;
    margin:0;
    padding:0
}

.outer-div {
    height: 100%;
    width: 100%;
    background-color: #f3f3f3;
}

.inner-div {
    width: 80%;
    height: 80%;
    background-color: #ccc;
    margin:auto;
    position: absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
}
4dgaurav
  • 11,360
  • 4
  • 32
  • 59
1

The important part is

position: absolute;
top:0;
bottom:0;
left:0;
right:0;

that will apply to the first parent that has position: relative or to body if nothing else has it.

phaberest
  • 3,140
  • 3
  • 32
  • 40