两个相对定位的div重叠在一起。

3

我有以下代码:

body {
  padding: 0;
  margin: 0;
}
.container {
  width: 30%;
  margin: 0 35%;
  background: yellow;
  position: relative;
  height: 900px;
}
.p1_1 {
  position: relative;
  width: 50%;
  height: 70%;
  top: 10%;
  left: 0;
  background-color: green;
}
.p1_2 {
  position: relative;
  width: 100%;
  height: 20%;
  border: 1px solid blue;
  top: 0;
}
<div class="container">
  <div class="p1_1">
    top box
  </div>
  <div class="p1_2">
    hello box
  </div>
</div>

我的问题是为什么.p1_1的前10%影响了.p1_2的位置?我原本以为这只是第二个div的简单相对定位 - 除非我漏掉了什么非常明显的东西?
好的 - 所以下面的代码更接近我的预期,但是有15%的空间而不是10%(即设置margin-top:15%可以正常工作),所以我很困惑70+10+20怎么不能等于100呢?
html,body { 
    padding:0; 
    margin:0;
    height:100%;                    
    position:relative;
}

.container {
    width:30%;
    margin:0 35%;
    background:yellow;
    position:absolute;
    height:100%;
    top:0;
}

.p1_1 {
    position:relative;
    width:50%;
    height:70%;
    margin-top:10%;
    background-color:green;
}

.p1_2 {
    position:relative;
    width:100%;
    height:20%;
    background-color:blue;
}       

我还发现第二个选项卡上的http://www.barelyfitz.com/screencast/html-training/css/positioning/解释了如何定位。
引用中说:“请注意,如果我们没有移动div-1,它通常会在哪里,现在是一个空白的空间。当我们移动div-1时,下一个元素(div-after)没有移动。这是因为div-1仍然占据文档中的原始空间,尽管我们已经将其移动。”

2
你期望什么? - j08691
1
“.p1_1” 不影响 “.p1_2”。“.p1_1” 出现在 “.p1_2” 的后面。 - hungerstar
3
相对定位是指元素在文档流中占据原本的空间,但在视觉上从该位置移动。 - hungerstar
1
不,我的意思是宽度。改变容器的宽度,你会看到上边距会改变。 - Asons
1
这篇文章描述得很好:https://dev59.com/k2gu5IYBdhLWcg3w4665 - Asons
显示剩余7条评论
1个回答

0

以下是一种方法,如何将两个div向下推10%,基于它们的父元素高度,使它们保持为父元素的70%和20%。

body {
  padding: 0;
  margin: 0;
}
.container {
  width: 30%;
  margin: 0 35%;
  background: yellow;
  position: relative;
  height: 900px;
}
.p1_1 {
  position: relative;
  width: 50%;
  height: 70%;
  left: 0;
  top: 10%;
  background-color: green;
}
.p1_2 {
  position: relative;
  width: 100%;
  height: 20%;
  border: 1px solid blue;
  top: 10%;
}
<div class="container">
  <div class="p1_1">
    top box
  </div>
  <div class="p1_2">
    hello box
  </div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接