Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maximizing a child div's height within a parent div

Tags:

javascript

css

I have a simple div setup:

<div id="container">
    <div id="title"><h4>Title</h4></div>
    <div id="content"></div>
</div>

The #container element is set to a fixed height. I would like to have #content us all the available height, but I haven't found a clean cross-browser way to do this. Here is the CSS:

div {
  width: 100%;
}
#container {
  height: 400px;
}
#content {
  height: 100%;
}

But this results in #content having the same height as #container and overflows its parent.

A live example can be seen at http://jsbin.com/amekah/2/edit.


I should note that I'm writing a JavaScript library that appends the #content div to an input div element (#container in this example) so I don't want to fiddle too much with the layout of either the parent element or any child elements. I don't mind using JavaScript to calculate the available height dynamically.

like image 316
Gingi Avatar asked Dec 26 '12 15:12

Gingi


1 Answers

Ridiculously easy with Javascript. I'm currently doing something like that on my current project.

  1. Get the Height of the Container: elem.offsetHeight where elem is a javascript pointer to the object. In your example this would be:

    var containerHeight = document.getElementById('container').offsetHeight.

  2. Get the Height of Child Elements in the Container: Here's a link on how to properly get childNodes. Here's what I'd do:

    var lastChild = elem.childNodes[elem.childNodes.length - 1];
    var verticalOffset = lastChild.offsetTop + lastChild.offsetHeight; 
    

Now you have the height of the container AND the vertical offset from the top of the parent to the last child plus the height of the last child.

All that's left to do is calculate the difference and assign it as the height of #content.

document.getElementById('content').style.height = (containerHeight - verticalOffset) + "px";   

EDIT: Proof of Concept

like image 168
akamaozu Avatar answered Sep 26 '22 18:09

akamaozu