2011-08-29 59 views
0

我有兩個div:一個包含複雜背景,另一個包含內容。它們都具有相同的基本風格:我的內容和背景都是絕對定位的div - 我如何拉伸背景div來匹配內容的高度?

#content, #background 
{ 
position:absolute; 
left:0px; 
top:0px; 
width:100%; 
height:100%; 
} 

這工作得很好,直到(例如)內容恰好是比窗口更長。在這種情況下,內容從背景中溢出(不會伸展以包含它)。

我如何獲得始終至少與內容一樣高的背景?我試圖把content div放在背景div裏面,或者把它們放在一個容器中 - 但它沒有改變任何東西。


編輯 - 這裏是說明我的問題簡化的標記;請注意,此人擁有背景div內的內容,因爲這更有可能發揮作用。

<style> 

#background 
{ 
position:absolute; 
left:0px; 
top:0px; 
width:100%; 
height:100%; 
} 

#sky, #background-level-1, #background-level-2, #background-level-3 
{ 
width:100%; 
position:absolute; 
left:0px; 
} 

#sky 
{ 
top:0px; 
height:100%; 
background:#ccf; 
z-index:10; 
} 

#background-level-1 
{ 
bottom:0px; 
height:100px; 
background:#9c9; 
z-index:103; 
} 
#background-level-2 
{ 
bottom:100px; 
height:50px; 
background:#696; 
z-index:102; 
} 
#background-level-3 
{ 
bottom:150px; 
height:25px; 
background:#363; 
z-index:101; 
} 

#content 
{ 
width:400px; 
height:1200px; 
border:#990 solid 1px; 
background:#ffc; 
z-index:200; 
position:absolute; 
margin:64px; 
padding:16px; 
} 

</style> 

<div id="background"> 

    <div id="sky"></div> 

    <div id="background-level-1"></div> 
    <div id="background-level-2"></div> 
    <div id="background-level-3"></div> 

    <div id="content"> 
    I need this element to stretch its parent (the div #background).<br> 
    The green divs contain pictures of hills and have a parallax effect applied to them through javascript. 
    </div> 

</div> 

編輯 - 好吧,這裏是爲我工作:

  • 把內容背景的div
  • 添加min-height:100%;height:100%;到後臺DIV
  • 添加position:relative;裏面內容

謝謝大家誰幫助。

+0

我們可以看到格結構,包括它們的父節點? –

+0

他們不在裏面 - 直接在。 – Orteil

回答

1

設置爲#backgroundposition: fixed這樣,它會堅持滾動。

但是,這不是一個更好的解決方案嗎? :

#content { 
    position:absolute; 
    left:0px; 
    top:0px; 
    width:100%; 
    height:100%; 
    background: <WHATEVER BACKGROUND #background USED TO HAVE> 
} 

OP聲明這是不可能的。


你可以做的另一件事,就是窩他們,就像這樣:

<div id=background> 

    <div id=content> 

    </div> 

</div> 

這樣的話,你只能絕對位置#background#content會默認自動拉伸它裏面的內容,因爲這是嵌套div的正常行爲。

+0

謝謝,但沒有,因爲我的背景是一個複雜的背景,有幾層和一些動態腳本巫術。另外我想把它設置爲固定會起作用,但那不是我正在尋找的。如果一切都失敗了,我想我會回到那個...... – Orteil

+0

在這種情況下,你可以將它們嵌套。我會更新答案。 –

+0

正如我的問題所述,我曾嘗試將內容div放在背景div中,但這不起作用;我認爲這是由於內容div有一個位置:絕對的(這對其他事物是必需的) - 此外,它與背景中的其他元素混淆很糟糕。不管怎麼說,還是要謝謝你。 – Orteil

0

你可以使用一個小JS行動來完成這件事:

<script type='text/javascript' 
src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script> 
<script type='text/javascript'> 
$(window).load(function() { 
// get the heights 
b = $('#background').height(); 
c = $('#content').height(); 

// get maximum heights of all 
h = Math.max(b, Math.max(c)); 

// apply it 
$('#background').height(h); 
$('#content').height(h); 
}); 
</script>