2011-09-20 51 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