Set div to remaining height using CSS with unknown height divs above and below

danial picture danial · Dec 19, 2011 · Viewed 64.4k times · Source

Is it possible to make the wrapper fill the window height (no scrolling) and the center div scrollable without messing around with pixels and javascript?

<div id="wrapper">
  <h1>Header</h1>
  <div id="center">
    <div style="height:1000px">high content</div>
  </div>
  <div id="footer">Footer</div>
</div>

Basically I want the header to be visible at the top and the footer to be always visible at the bottom and have a scrollable content in the center which occupies the remaning height.
The header, footer and center divs' heights are all unknown (no set px or %, i.e. variable font-size or padding). Is it possible with pure CSS?

Answer

Dan Dascalescu picture Dan Dascalescu · Sep 3, 2012

2014 UPDATE: The modern way to solve this layout problem is to use the flexbox CSS model. It's supported by all major browsers and IE11+.


2012: The correct way to do this with CSS alone is to use display: table and display: table-row. These are supported by all major browsers, starting with IE8. This is not using tables for display. You'll use divs:

html, body {
    height: 100%;
    margin: 0;
}
.wrapper {
    display: table;
    height: 100%;
    width: 100%;
    background: yellow;  /* just to make sure nothing bleeds */
}
.header {
    display: table-row;
    background: gray;
}
.content {
    display: table-row;  /* height is dynamic, and will expand... */
    height: 100%;        /* ...as content is added (won't scroll) */
    background: turquoise;
}
.footer {
    display: table-row;
    background: lightgray;
}
<div class="wrapper">
    <div class="header">
        <h1>Header</h1>
        <p>Header of variable height</p>
    </div>
    <div class="content">
        <h2>Content that expands in height dynamically to adjust for new content</h2>
        Content height will initially be the remaining
        height in its container (<code>.wrapper</code>).
        <!-- p style="font-size: 4000%">Tall content</p -->
    </div>
    <div class="footer">
        <h3>Sticky footer</h3>
        <p>Footer of variable height</p>
    </div>
</div>

That's it. The divs are wrapped as you'd expect.