Two divs on top op each other, together exact height 100% + lower div scrollable

ravax picture ravax · Aug 18, 2013 · Viewed 13.2k times · Source

I'm stuck with this problem:

I have a div (#container) which contains two divs. The height of the container should be exact 100%, regardless of the content of this div - not less not more.

Inside this div I want two full-width divs on top of each other:

  • The (#upper) div's content automatically determines its height.
  • The (#lower) div's content should be scrollable, but only vertically. Its height is dependent on the height of (#upper): 100% - (#upper)height = (#lower)height

Currently I have the following css ...

body {
    margin:0;
    padding:0;
    }
#container 
    {
    position: relative;
    width: 500px;
    height: 100%;
    max-height: 100%;
    background-color: #f00;
    }
#upper { 
    width: 100%;
    background-color: #0f0;
    }
#lower {
    width: 100%;
    background-color: #00f;
    overflow: auto;
}

... as well as this code:

<div id="container">
<div id="upper"></div>
<div id="lower"></div>
</div>

How can the (#container)'s height be exactly 100% - independent of its content? Now the height becomes larger because of the combined content of (#upper) and (#lower)?

How can (#lower) be scrollable (only up and down, not left to right!)?

Thank you very much for your feedback, I hope we can all learn from this.

Answer

John Woodruff picture John Woodruff · Aug 18, 2013

You should set your html and body elements to have a height of 100%, so your children divs know what to base the percentage off of. Like so:

html, body {
    height:100%;
    width:100%;
}

Change your container to this:

#container 
{
    width: 500px;
    height: 100%;
    background-color: #f00;
}

As for your scrolling issue, you're almost there. Change the code to the following:

#lower {
    width: 100%;
    height:100px;
    background-color: #00f;
    overflow-y: auto;
}

For it to work best, have a fixed height set on your lower div and that'll make it easy for the scrollable action to work best.

EDIT:

I realized I mis-read your question. You'd like to have your lower div fill the remaining height of the window. Here's how to do that in jquery:

var top = $('#upper').height();
var remaining_height = parseInt($(window).height() - top); 
$('#lower').height(remaining_height); 

I still haven't found a way to do that with only CSS... Sadly.