2010-01-07 68 views
8

我有一個div有兩個嵌套的div。第一個孩子根據其內容有不同的高度,我希望第二個孩子的高度是父母留下的任何東西。如何讓DIV佔用容器div的其餘高度?

<div style="height:500px;"> 
    <div>Some Content Here</div> 
    <div>This div needs to take up the rest of the space of its parent</div> 
</div> 

我該怎麼做?

感謝,在聖地亞哥

+3

相同http://stackoverflow.com/questions/1818467/how-to-apply-100-height-to-div? – Upperstage 2010-01-07 20:46:23

+0

忘記Java腳本解決方案或黑客用表格佈局[此處輸入鏈接的描述] [1] [1]:http://stackoverflow.com/a/26558049/869661 – Kryszal 2015-08-25 20:35:29

回答

8

〜CK它需要一些JavaScript。我看到你使用jQuery,所以這應該工作:

給予一定的ID到父DIV:

<div style="height:500px;" id="parent"> 
    <div>Some Content Here</div> 
    <div>This div needs to take up the rest of the space of its parent</div> 
</div> 

然後在jQuery的:

$('div#parent div:last').each(function() { 
    var p = $(this).parent(); 
    $(this).height(p.height() - ($(this).offset().top - p.offset().top)); 
}); 
+1

無視我的意見,因爲我錯了= x – Erik 2010-01-07 20:52:53

2

我想我已經得到了正確的方法來做它沒有Javascript:

<div style="height:500px; background:pink; overflow: hidden"> 
    <div style="background: yellow">stuff</div> 
    <div style="height: 100%; background: red;">This div needs to take up the rest of the space</div> 
</div> 

關鍵是「溢出:隱藏」在主div,作爲設置高度的第二個div到100%,使它500像素高。

+4

但是如果填充(紅色)div的內容太大(即高於500px - 紅色div的高度),它將被切斷。這可能很難看,取決於紅色div的內容。 – AUSteve 2010-01-10 11:11:24