Bogdan
Bogdan

Reputation: 1901

How can I dynamically change the height of a div to match the size of the div containing it

I got div1 and div2 with div2 containing div1 (and some other elements). I want to dynamically change the height of div1 to match the height of div2(- the height of the other elements) whenever div1 exceeds that height. The reason I don't just set div1's height outright is because div2's size isn't fixed and I want the horizontal scroll bar from div1 to stick to the bottom of its content and not to the bottom of div2.

I don't have any code to show since it's just two divs.

If it helps, div1 will contain a table.

Here's what I got so far:

if(document.getElementById("div1").offsetHeight > document.getElementById("div2").offsetHeight) {       
    document.getElementById("div1").style.height = document.getElementById("div1").parentNode.offsetHeight+"px";
    document.getElementById("div1").style.overflowY = "scroll";                             
}

This works for setting the overflow but I can't get it to actually change the height of div1

Here's the working version:

document.getElementById("div1").style.height = '';
document.getElementById("div1").style.overflowY = "";   
if(document.getElementById("div1").offsetHeight > document.getElementById("div2").offsetHeight) {   
    var height = document.getElementById("div2").offsetHeight - document.getElementById("other_data").offsetHeight;
    document.getElementById("div1").style.height = parseInt(height)+"px";
    document.getElementById("div1").style.overflowY = "scroll";                             
}

for those who might be having the same problem.

Upvotes: 3

Views: 14562

Answers (1)

tkone
tkone

Reputation: 22728

Something like this would work. You can write an event listener to watch for page resize, of if you're dynamically changing the size of the "parent" div tag, you should just call the js code to resize the child div each time.

HTML:

<div id=div1><div id=div2></div></div>

JS:

div2 = document.getElementById('div2')
div2.style.height = div2.parentNode.offsetHeight+"px"

Upvotes: 2

Related Questions