2011-09-20 45 views
6

我使用浮點定位(例如用overflow:hidden解決問題)時,處理了divs在其內容上崩潰的問題,但我試圖學習絕對/相對定位,並且無法弄清楚爲什麼container div崩潰。我的測試案例:爲什麼div相對/絕對定位崩潰?

<html> 
    <head> 
    <style type="text/css"> 
     body { 
     background-color:#eee; 
     } 

     #content { 
     margin:0 auto; 
     position:relative; 
     border:1px solid red; 
     width:800px; 
     display:block; 
     background-color:white; 
     } 

     #header { 
     border:1px solid black; 
     background-color:#777; 
     color:white; 
     width:800px; 
     position:absolute; 
     left:0; 
     top:0; 
     } 

     #leftcol { 
     position:absolute; 
     border:1px solid black; 
     background-color:#ddd; 
     width:200px; 
     top:100px; 
     left:0; 
     } 

     #rightcol { 
     position:absolute; 
     top:100px; 
     left:205px; 
     border:1px solid black; 
     background-color:#ddd; 
     width:500px; 
     } 

    </style> 
    <title>CSS Positioning Example 1</title> 
    </head> 

    <body> 
    <div id="content"> 

     <div id="header"> 
     <h1>The Awesome Website</h1> 
     </div> 

     <div id="leftcol"> 
     <h2>About</h2> 
     <p> 
     This website is so awesome because it was made by someone 
     and that is really all there is to it. There. 
     </p> 
     </div> 

     <div id="rightcol"> 
     <p>This is where I'm going to put some real body text so that it goes 
     on and on for a while and so I can get a sense of what happens when 
     the text in the paragraph keeps going and the box containing it keeps 
     going on as well. 
     </p> 
     </div> 

    </div> 

    </body> 
</html> 

這是怎麼回事?爲什麼紅色邊框的內容div即使包含其他div也會崩潰?

+0

JSBin:http://jsbin.com/exukoc – Mohsen

回答

8

這是因爲它的所有內容都被設計爲position:absolute。這將這些元素從流中排除,並且(佈局方式)就像它們不存在一樣。考慮使用position:relative來定位內容。

+0

ty用於拼寫和語法校正,@sscirrus。晚了。 :P –

+0

我認爲使用絕對定位元素的意義在於將它們放置在相對定位的祖先內?不是位置:相對於它的祖先絕對嗎? – mix

+0

@約瑟夫 - 當然!很好的答案,還有我的+1。 – sscirrus

3

你真的需要在列表讀這些文章除了

CSS Positioning 101

CSS Floats 101

你的問題是爲什麼用紅色邊框股利不擴展到它的內容。正如Joseph所說的那樣,問題在於你從文檔流中取出元素。定位元素絕對使元素的位置獨立於其父代和兄弟。

我使用CSS float property修復了您的代碼。看看here

我強烈建議你閱讀這些文章。

+0

thx爲偉大的聯繫。完全有幫助。 – mix