Rango
Rango

Reputation: 2106

How to set height of div match its container

I have a div which is container. This div contain 2 div tags, as below:

<style type="text/css">
#container{
    height:100%
}

#child1{
    height:35px;
}

#child2{
    overlow-y:auto;
    height: ??? /**to match remain space of container**/
}
</style>


<div id="container">
    <div id="child1">this is a child1</div>
    <div id="child2">this is a child2</div>
</div>

How can I set child2's height to match remain space of container which is vertical scroll bar if child2's content is too much?

Upvotes: 0

Views: 7431

Answers (5)

James Montagne
James Montagne

Reputation: 78760

An alternative solution would be to use calc:

#child2{
    overflow-y: auto;
    height: calc(100% - 35px);
}

http://jsfiddle.net/AMQ8f/1/

IE9+ http://caniuse.com/calc

Upvotes: 2

James Montagne
James Montagne

Reputation: 78760

One option is to use a mix of relative and absolute positioning:

#container{
    height:100%;
    position: relative;
}

#child1{
    height:35px;
}

#child2{
    overflow-y:auto;
    position: absolute;
    width: 100%;
    top: 35px;
    bottom: 0;
}

You don't actually set the height at all, you make the element 35px from the top and 0px from the bottom.

http://jsfiddle.net/AMQ8f/4/

Upvotes: 3

Udit Bhardwaj
Udit Bhardwaj

Reputation: 1781

there is an error or i think its a typo in your css overlow-y

create a function to adjust height of child2 that will be called when the page loads and on the event which changes the height of the container

DEMO & CODE

NOTE:- scroll the fiddle output there is a button below the container to change the height of container

$(document).ready(function(){
    setHeight();

     $('#change').click(function () {
        $('#container').css('height', '300px');
        setHeight();
     });

});

function setHeight (){
    $('#child2').css('height', $('#container').height() - 35 + 'px');
    $('#child2').css('max-height', $(this).height())
}

Upvotes: 1

Merijn Den Houting
Merijn Den Houting

Reputation: 199

You could try using the calculate function

      height: calc(100%-35px)
      height: -webkit-calc(100%-35px)
      height: -moz-calc(100%-35px)

I have never actually used this and probably not all browser will support this, but I though it could work.

Upvotes: 1

Roukas
Roukas

Reputation: 36

I don't understand your question, I assume you want it to scroll? if so

child2{
overlow-y:scroll;
height: 100%;
}

I hope this helps

Upvotes: 0

Related Questions