views:

655

answers:

4

hi, i'm having the following markup using 2 divs. the #child div has set position:absolute;

+------------------------------+
|    +----------+              |
|    | #child   |              |
|    +----------+              |
|                              |
|                              |
|                              |
+------------------------------+

i want to change the child's height by code so that it always auto-sizes to its container like this:

+------------------------------+
|    +----------+              |
|    | #child   |              |
|    |          |              |
|    |          |              |
|    |          |              |
|    +----------+              |
+------------------------------+

is there a default function for it? thx

A: 
<div id="parent">
  <div id="child"></div>
</div>

with:

#parent { position: relative; background: red; height: 500px; width: 700px; }
#child { position: absolute; background: yellow; height: 80%; top: 10%; bottom: 10; left: 100px; width: 300px; }

Note: the child's height is relative (80%) to the parent's height so no matter what you set the height of the parent to or dynamically resize it to, it'll change the height of the child but the parent must have an explicitly set height (even if its 100%) or this won't work.

cletus
A: 

Try something like this (rough approximation, adjust to your needs)

$('#child').css('left', '20%').css('top','10%').css('height','80%').css('width', '30%');
axel_c
This would size the child div relative to the page size, not the parent div.
James
@James Goodwin: uh? it would set the child relative to the parent div, not the page.
axel_c
Sorry I was thinking for some reason because it was absolute it would use the height of the page instead, but in fact you are right! :)
James
A: 

try;

$('#child').height($('#child').parent().height());

this assumes that you have no padding and borders on your outer div. if you do you will need to take these off the height in some browsers to ensure it matches.

Matt Smith
A: 

Since you tagged with jQuery I will provide you with a jQuery style solution too:

$("#child").height($("#parent").height()*0.8);
James