12

This question seems to have been answered a gazillion times in various forms but I still can't find an answer that works for me. Put simply, I have this layout:

<body>
    <div class="wrapper">
        <div class="header"></div>
        <div class="body"></div>
        <div class="footer"></div>
    </div>
</body>

I want wrapper to be centered horizontally in the browser and for it to fill 100% of the browser's height. Each of the enclosed <div> elements has a fixed height that more often than not sum to a height that is greater than the browser window's height. If this is the case, I get the layout I want.

If, however, the browser window's height is greater than the combined height of the enclosed <div> elements (as is the case on an iMac or portrait iPhone orientation, for example), then the wrapper seems to stop with the end of the footer and the rest of the window below this is <body> background. The wrapper background and <body> background are different colours, so it is quite obvious that this is the case.

Does anyone have a CSS solution to this, so that the wrapper fills the browser height regardless of whether this height is greater or less than the combined height of the content?

EDIT: ANSWER:

The answer was a combination of the answers below and something that I happened upon just now: In the CSS, do this:

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

.wrapper {
    height:     auto;       /* These two lines were the key. */
    min-height: 100%
    /*overflow:   hidden;*/ /* Do not use this, it crops in small browsers. */
    margin:     0px auto;
    padding:    0px auto;
 }
Ed King
  • 1,833
  • 1
  • 15
  • 32

3 Answers3

13

If you want to set a div height to 100%, you should set the height of html and body to 100% as well. Then you can add 100% to the div.

CSS

.wrapper {
border: 1px solid red;
height: 100%;
margin: 0px auto;
overflow: hidden;
}

body, html {
height: 100%;
}

Take a look at this jfiddle.

Benjamin
  • 1,983
  • 23
  • 33
  • Thanks. All the answers have been along the same lines, but it seemed the key was the `overflow: hidden` part. I now have the layout I want in each type of orientation. – Ed King Sep 09 '13 at 09:19
  • Actually, this is still not right - the `overflow:hidden` chops the content in landscape iPhone orientation. Any thoughts? – Ed King Sep 09 '13 at 09:22
  • Adding overflow-x: auto will add a vertical scrollbar when your divs are bigger than your wrapper. – Benjamin Sep 09 '13 at 11:02
1

If you want to have an element that fills 100% the height of the viewport, you need to have:

body, html {
  height: 100%;
}

#wrapper {
  height: 100%;
}
António Regadas
  • 714
  • 4
  • 11
0

for centering wraper div

body{
   margin:0px;
   padding:0px;
  height:100%;
}
.wraper{
   width:90%;
   margin:0px auto;
  height:100%;
  overflow:hidden
}
Love Trivedi
  • 3,899
  • 3
  • 20
  • 26