2016-02-01 146 views
3

我有以下代码:两个相对的div互相重叠

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/选项卡上的2说明如何

“注意这里DIV-1,如果我们没有 移动它通常会一直空间:现在是一个空的空间。当我们移动div-1时,下一个元素(div-after)没有移动,这是因为div-1仍然占据了文档中的原始空间,即使我们移动了它。

+2

什么是你期待? – j08691

+1

'.p1_1'不会影响'.p1_2'。 '.p1_1'出现在'.p1_2'后面。 – hungerstar

+0

好的 - 但如果它的位置相对较低,为什么它不会推下第二个呢? – Ukuser32

回答

0

这里有一种方法是如何根据父母的身高将2格降低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>