2009-09-05 122 views
2

首先,對於該標題感到抱歉。我不是寫這些東西最好的。使容器div爲一個子div的高度,並使容器的其他子div高度爲

我有一個包含兩個div(#a和#b)的容器div(我們稱之爲#container)。我無法控制這兩個div的內容。

我想#container是#a的高度。我還希望#b將伸縮(或收縮,取決於)到#container的100%,並在必要時有滾動條。

這聽起來像應該是非常容易,但我花了幾個小時試圖讓這個工作。

如果這是不可能的,我會解決這個問題: #容器有固定的高度,#b有固定的高度。 #a有兩個塊級元素(#1和#2),它們具有不可控制的高度。 #2應該是#a的100%,減去#1的高度。

請告訴我其中一個可能!

+1

發佈一些代碼或詳細說明您的頁面佈局。 – adatapost 2009-09-05 08:22:40

+0

你的第一個要求是#container是#a的高度,這意味着如果你想顯示#b,總會有一個滾動條,因爲#a需要#container的所有高度 – 2009-09-05 08:29:04

+0

你願意爲幾個JavaScript的行? – 2009-09-05 08:52:52

回答

1

我喜歡這些CSS變化(以一種自虐的方式)。我很吃驚想出了一個解決方案:

<html> 
<head> 
<style type="text/css"> 
html, body, div { margin: 0; padding: 0; } 
#container { width: 600px; height: auto; margin: 0 auto; background: orange; position: relative; } 
#left { background: green; width: 300px; } 
#right { overflow: auto; background: yellow; width: 300px; position: absolute; top: 0; bottom: 0; right: 0; } 
</style> 
</head> 
<body> 
<div id="container"> 
<div id="left"> 
<p>f this is not possible, I would settle for this: #container has a fixed height, #b has a fixed height. #a has two block-level elements (#1 and #2) that have uncontrollable heights. #2 should be 100% of #a, minus the height of #1.</p> 
<div id="right"> 
<p>I have a container div (let's call it #container) which contains two divs (#a and #b). I am not in control of the content of these two divs.</p> 
<p>I want #container to be the height of #a. I also want #b to stretch (or shrink, depending) to 100% of #container, and have a scrollbar, if necessary.</p> 
</div> 
</div> 
</body> 
</html> 

試試吧,其中左邊是比對大,它仍然有效。

這可能值得添加一個DOCTYPE來強制IE進入一個稍微不吸引人的模式。

+0

令人驚歎!這很好用!非常感謝。 – Alan 2009-09-05 17:17:30

+0

經過一番工作,這還不完美。它不能在IE6中工作,如本ALA文章中所述:http://www.alistapart.com/articles/conflictingabsolutepositions/(curses!) 因爲我已經有了IE6的條件樣式表,我只是絕對定位了div #右上角,並給它一個固定的高度。它不會伸展到#container的高度,但至少它不會像以前那樣直接穿過#container的底部。 – Alan 2009-09-12 23:18:46