2016-09-28 152 views
0

我有基本的CSS佈局isssue。 DIV2上升150px,部分重疊DIV1。將DIV3放在DIV2下方時遇到問題。我可以使用與DIV2中相同的CSS來應用DIV3,但那不是我正在尋找的,因爲它們還有很多其他的div,而且我似乎也必須對其他所有的div都這樣做。必須有一些東西來重置職位。我希望我清楚地解釋自己。 DIV2的高度也必須靈活(移動)。CSS位置 - 部分重疊div

視覺圖:

enter image description here

CSS DIV2:

position: relative; 
top: -150px; 

HTML:

<div class="div1"></div> 
<div class="div2"></div> 
<div class="div3"></div> 
+0

不應該你的第二個'div2'類是真正'div3'?你已經在共享的HTML代碼中聲明瞭'div2'類。 –

回答

1

使用margin-top,而不是在CSS top財產。其餘的div將在div2之後自動執行。

如果仍然無效,請分享您代碼的工作小提琴。

div { 
 
    width: 300px; 
 
    height: 150px; 
 
} 
 
.div1 { 
 
    background: red; 
 
} 
 
.div3 { 
 
    background: green; 
 
} 
 
.div2 { 
 
    margin: 0 auto; 
 
    margin-top: -50px; 
 
    background: yellow; 
 
    width: 150px; 
 
} 
 
.parent { 
 
    width: 300px; 
 
    margin: 0 auto; 
 
}
<div class="parent"> 
 
    <div class="div1"></div> 
 
    <div class="div2"></div> 
 
    <div class="div3"></div> 
 
    <div class="div1"></div> 
 
    <div class="div3"></div> 
 
</div>

+0

使用margin-top而不是top可以實現。謝謝。 – Nita

1

添加到您的div2,雖然它不是最好的做法:

margin-bottom: -150px

.div1, 
 
.div2, 
 
.div3 { 
 
    height: 150px; 
 
} 
 

 
.div1 { 
 
    background: red; 
 
} 
 

 
.div2 { 
 
    background: blue; 
 
    position: relative; 
 
    top: -75px; 
 
    margin-bottom: -75px; 
 
} 
 

 
.div3 { 
 
    background: green; 
 
}
<div class="div1"></div> 
 
<div class="div2"></div> 
 
<div class="div3"></div>

+0

不起作用,我試過已經 – Nita

+0

什麼將是最佳做法? – Nita

+0

我已經向我的答案添加了一個示例,顯示負邊距工作正常。 – Christoph