【问题标题】:why does div collapse with relative/absolute positioning?为什么 div 会随着相对/绝对定位崩溃?
【发布时间】:2011-11-20 17:49:12
【问题描述】:

我已经处理了使用浮动定位时 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 却会塌陷?

【问题讨论】:

标签: css positioning css-position


【解决方案1】:

这是因为它的所有内容都被样式化为position:absolute。这会使这些元素失去流动性,并且(布局方面)就像它们甚至不存在一样。考虑使用position:relative 来定位内容。

【讨论】:

  • ty 用于拼写和语法更正,@sscirrus。现在已经晚了。 :P
  • 我认为使用绝对定位元素的目的是将它们放在相对定位的祖先中? position:absolute 不是相对于它的祖先吗?
  • @mix - absolutes 相对于它们的祖先,但它们仍然不在其祖先中的 其他 元素的流动范围内。
【解决方案2】:

你真的需要在 A List Apart 阅读这些文章

CSS Positioning 101

CSS Floats 101

您的问题是为什么带有红色边框的 div 不会扩展到它的内容。正如约瑟夫所说,问题在于您将元素从文档流中取出。定位元素绝对使元素的位置独立于其父元素和兄弟元素。

我使用CSS float property 修复了您的代码。看看here

我强烈建议您阅读这些文章。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-14
    • 2012-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多