2013-10-13 43 views
0

我有一個包含2個div的div,其中一個具有固定的高度。 我想確保第二個div的高度與容器div的高度減去其他div的高度一樣多。這個高度不能手動設置,因爲它經常調整大小。CSS/JavaScript:根據容器大小保留div大小

<div id="container" style="height: 50%"> 
<div id="header" style="height: 30px;"> 
</div> 
<div id="content"> 
</div> 
</div> 

我曾嘗試與調整大小jQuery的,但我想我寫的東西錯了:

$(document).on("resize", "#container", function (event) { 
    $('#content').height($('#container').height()-$('#header').height()); 
}); 

有什麼辦法(使用Javascript,CSS)來實現這一目標?

+0

是否頭必須是' 30px'正好? –

+0

身高:100%,不是? –

+0

是的,它必須是30px。和高度100%會使它比容器大30px – valepu

回答

1

你的主要問題似乎是,你必須大小的元素開始,然後繼續聽resize事件:

function handleResize() { 
    $('#content').height($('#container').innerHeight()-$('#header').height()); 
} 

$(window).on("resize", handleResize); 

handleResize(); 

此外,調整大小事件應該被直接連接到窗口。

否則,我建議使用innerHeight()作爲考慮填充的容器。

我也做了一些修正,以你的CSS這個工作充分:

#container { 
    position: absolute; 
    width: 100%; 
    height: 50%; 
} 

查看完整的小提琴的位置:http://jsfiddle.net/kjcY9/1/

+0

謝謝,這工作 – valepu

2

對jQuery還有另外一種方法CSS Flexbox的:

#container { 
    display: flex; 
    flex-direction: column; 
} 

#content { 
    flex: 1; 
} 

請參閱demo。不幸的是,這隻適用於支持最新Flexbox語法的瀏覽器。 (http://caniuse.com/#search=flexbox)向後兼容的代碼也可以使用舊的語法,但是會更加複雜。有關如何做到這一點的更多信息,請參閱David Storey的文章http://coding.smashingmagazine.com/2013/05/22/centering-elements-with-flexbox/

0

我要給你一個純CSS的解決方案, 檢查出Working Fiddle

HTML:

<div id="container"> 
    <div id="header"></div> 
    <div id="content"></div> 
</div> 

CSS:

#container { 
    height: 300px; /*Whatever fixed height you want*/ 
} 
#container:before { 
    content:''; 
    float: left; 
    height: 100%; 
} 
#header { 
    height: 30px;/*Whatever fixed height you want, or not fixed at all*/ 
    background-color: red; 
} 
#content { 
    background-color: blue; 
    /*No height spesified*/ 
} 
#content:after { 
    content:''; 
    clear: both; 
    display: block; 
}