代码之家  ›  专栏  ›  技术社区  ›  Matt

为什么一个元素会随着位置的改变而改变:相对的元素仍然像没有被移动一样对父维度有贡献?

  •  0
  • Matt  · 技术社区  · 14 年前

    position: relative;
    top: -50px;
    

    仍然强制父元素具有相同的大小,就好像相对定位的元素没有移动一样?

    让我举一个例子(在 http://jsbin.com/ohebi4/2/edit

    <html>
    <head>
      <style>
          article, aside, figure, footer, header, hgroup,
          menu, nav, section { display: block; }
    
          .parent{ position: relative; background-color: #000000; float: left; border: 1px solid red; }
          .child1{ float: left; background-color: #888888;}
          .child2{ float: left; background-color: #CCCCCC; }
    
          .subchild{ position: relative; top: -45px; height: 30px; border: 1px solid green;}
          .subchild2{ height: 30px; border: 1px solid green;}
        </style>
    </head>
    <body>
    
      <div style='clear: both; height: 50px;'></div>
      <div class='parent'>
        <div class='child1'>regular content</div>
        <div class='child2'>content of child 2</div>
      </div>
      <div>Sample A</div>
    
      <div style='clear: both; height: 50px;'></div>
      <div class='parent'>
        <div class='child1'><div class='subchild2'>subchild</div></div>
        <div class='child2'>content of child 2</div>
      </div>
      <div>Sample B</div>
    
      <div style='clear: both; height: 50px;'></div>
      <div class='parent'>
        <div class='child1'><div class='subchild'>subchild</div></div>
        <div class='child2'>content of child 2</div>
      </div>
      <div>Sample C</div>  
    
      <div style='clear: both; height: 50px;'></div>
      <div class='parent'>
        <div class='child1'><span>child 1</span><div class='subchild'>subchild</div></div>
        <div class='child2'>content of child 2</div>
      </div>
      <div>Sample D</div>
    </body>
    </html>
    

    上面的标记创建的页面如下所示:

    alt text

    示例A:父div中只有几个div,具有正常的内容和流

    样本B:添加了一个子div,高度为30px。正如所料,它改变了父对象的高度,从而显示了“子对象b的内容”下面的黑色背景

    样本C:子孩子被重新定位位置:相对。请注意,即使此元素移到了所有元素之上,它仍然会影响父元素的高度,从而保持黑色背景的显示

    样本D:样本C中的问题通过在子子级div之前添加一个span而消除。

    我期望(显然是错误的)示例C(和D)看起来与A相同,并在上面添加了绿色的“subchild”框。

    有人能告诉我为什么会这样,怎么做吗

    1 回复  |  直到 14 年前
        1
  •  2
  •   Jeff Rupert    14 年前

    您必须设置:

    position:absolute;
    

    拥有 .subchild .parent position:relative; ,你不需要做任何其他事情。


    根据 this 位置:相对位置; position:absolute; 将使其不计算为正常流,并使用第一个父标记的左上角 位置:相对位置; 作为原点。(如果没有父母 relative fixed .) position:fixed; 始终使用视口左上角作为原点。