2009-06-17 226 views
1

这是我在修理布局时总是遇到的一个问题。我有一个绝对定位的DIV,我放置了一个儿童DIV,其中也需要绝对定位。但我真的希望这个孩子DIV相对于父母行为......这甚至有可能吗?或者我需要创建一个换行DIV?绝对定位DIV相对于(也绝对定位)父DIV的位置?

<div class="container" style="position:relative;"> 
    <div class="parent" style="position:absolute;"> 

     <!-- this child div will behave relative to .container --> 
     <div class="child" style="position:absolute;"></div> 
    </div> 
</div> 

这是“包装”的解决方案,我宁愿避免:

<div class="container" style="position:relative;"> 
    <div class="parent" style="position:absolute;"> 
     <div class="wrapper" style="position:relative;"> 

      <!-- this child div will behave relative to .wrapper--> 
      <div class="child" style="position:absolute;"></div> 
     </div> 
    </div> 
</div> 

回答

1

绝对定位的元素相对于未定位的其最近的祖先的边缘定位(即,不是位置:静态)。

由于父元素位置:绝对,子元素将相对于其边缘进行定位。

所以你似乎在问如何获得你已有的行为。您的第一个示例中的评论看起来不正确。

0

你可能要问自己,如果你确实需要使用多个嵌套绝对定位的元素。

否则,它可能是最好的包装解决方案。

1

如果你已经绝对定位一个div,你不能只为孩子添加两个偏移量吗?例如对于#one是在10,10和#two在10,10相对于#one,

#one { 
    position: absolute; 
    left: 10px; 
    top: 10px; 
} 

#two { 
    position: absolute; 
    left: 20px; 
    top: 20px; 
} 

或者是到左上角和#two到右下角的东西票友,像#one锁定#one,在这种情况下,基础数学不能以这种方式工作?在这种情况下,可能需要额外的div。

还是我只是累了,想念什么?