2017-08-29 77 views
0

我有兩個部分,第一部分是使用相對位置,幷包含2個絕對兒童與兒童覆蓋。第二部分包含一個標題。如何在文檔流中保留相對定位的父級?

我想保留第一部分的位置相對流動,所以第二部分出現在下面。我理解絕對位置在文檔流之外需要元素,但即使是相對父級,情況也是這樣嗎?

我該如何保持家長流動?

.parent { 
 
    position: relative; 
 
} 
 
.child { 
 
    color: white; 
 
    position: absolute; 
 
    width: 100%; 
 
} 
 
.child1 { 
 
    background-color: red; 
 
    z-index: 1; 
 
} 
 

 
.child2 { 
 
    background-color: blue; 
 
    z-index: 0; 
 
}
<div class="parent"> 
 
    <div class="child child1">block1</div> 
 
    <div class="child child2">block2</div> 
 
</div> 
 

 
<div class="text"> 
 
    <h1>block below</h1> 
 
</div>

回答

0

你只需要設置父元素的尺寸,所以它的孩子才能進行。由於絕對定位的孩子被取消了常規流程,這意味着父母的div不包含任何東西,因此它「消失」。即:

.parent { 
    position: relative; 
    width: 200px; 
    height: 200px; 
    background-color: Wheat; 
} 

而且片段:

.parent { 
 
    position: relative; 
 
    width: 200px; 
 
    height: 200px; 
 
    background-color: Wheat; 
 
} 
 
.child { 
 
    color: white; 
 
    position: absolute; 
 
    width: 100%; 
 
} 
 
.child1 { 
 
    background-color: red; 
 
    z-index: 1; 
 
} 
 

 
.child2 { 
 
    background-color: blue; 
 
    z-index: 0; 
 
}
<div class="parent"> 
 
    <div class="child child1">block1</div> 
 
    <div class="child child2">block2</div> 
 
</div> 
 

 
<div class="text"> 
 
    <h1>block below</h1> 
 
</div>

如果需要家長的div不退出的正常流動,那麼它應該是靜態的:

.child { 
 
    color: white; 
 
    position: relative; 
 
    width: 100%; 
 
} 
 
.child1 { 
 
    background-color: red; 
 
    z-index: 1; 
 
    position: absolute; 
 
} 
 

 
.child2 { 
 
    background-color: blue; 
 
    z-index: 0; 
 
}
<div class="parent"> 
 
    <div class="child child1">block1</div> 
 
    <div class="child child2">block2</div> 
 
</div> 
 

 
<div class="text"> 
 
    <h1>block below</h1> 
 
</div>

+0

我看到了,感謝您的回覆,我的問題是,我無法使用px作爲高度,因爲我的網站具有響應能力,它是否只能使用固定值工作? – Sai

+0

當然,你只需要將父母的位置設置爲靜態(因此,根本沒有位置),然後它就會工作,因爲它會回到流程中。我正在更新代碼段。 – Tedds

+0

我試圖在我的項目上實現這一點,但第一個孩子仍然將父母移出流程,我試圖用標籤實現它 – Sai

相關問題