2016-11-28 42 views
1

CSS只CSS絕對小孩

我想我有絕對定位div背後它的(相對)的父母, 但仍留在上面的它的父兄弟姐妹。 所以使用負z-index值不會幫助這裏...

fiddle實際上是我要找的對面: 父DIV(左)應該是綠色的孩子DIV的頂部和兄弟分區(右側)應該在它後面。

這裏的任何想法?

+0

檢查我的回答如下。讓我知道它是否有效 –

回答

3

看到這裏>jsfiddle

我也建議你添加一個不同的類,在具有.inner.container

,如:<div class="container parent">,然後在CSS .parent ~ *{z-index:-2}所以你一定所有它的兄弟姐妹有z-index:-2

或摘錄如下:

.container { 
 
    display: inline-block; 
 
    margin: 10px; 
 
    width: 50px; 
 
    height: 50px; 
 
    background-color: red; 
 
    position: relative; 
 

 
} 
 

 
.inner { 
 
    top: 5px; 
 
    left: -10px; 
 
    right: -50px; 
 
    bottom: -10px; 
 
    background-color: green; 
 
    position: absolute; 
 
    z-index:-1; 
 
} 
 
.container:not(:first-child) { 
 
    z-index:-2; 
 
}
<div class="container"> 
 
    <div class="inner"> 
 
    </div> 
 
</div> 
 
<div class="container"> 
 
</div>

+0

它確實有效,但我有兩個問題:1.其他元素的選擇器對於此示例非常具體(不適用於我的代碼)2.將z-index設置爲一個負面的我鬆散的懸停能力(我確實需要) – naomi

+0

好吧...如果你想讓我做出100%的工作答案,我需要更多的代碼 –

0

您可以按以下使用nth-child selector瞄準同一類.containertwo different parent div

.container:nth-child(1){ 
 
    display: inline-block; 
 
    margin: 10px; 
 
    width: 50px; 
 
    height: 50px; 
 
    background-color: red; 
 
    position: relative; 
 
} 
 

 
.inner { 
 
    top: 5px; 
 
    left: -10px; 
 
    right: -50px; 
 
    bottom: -10px; 
 
    background-color: green; 
 
    position: absolute; 
 
    z-index:-1; 
 
} 
 
.container:nth-child(2){ 
 
    display: inline-block; 
 
    margin: 10px; 
 
    width: 50px; 
 
    height: 50px; 
 
    background-color: red; 
 
    z-index:-2; 
 
    position:absolute; 
 
}
<div class="container"> 
 
    <div class="inner"> 
 
    </div> 
 
</div> 
 
<div class="container"> 
 
</div>

+0

爲什麼使用相同的樣式2次?只需使用所有具有「容器」類的div的共同只有一次的樣式,然後使用不同'container' div的特定樣式。例如,如果兩者都有'background-color:red'只寫一次'.container {background-color:red'}不是2次。 –

+0

@MihaiT是的你是對的,我的主要觀點是你可以在nth-child選擇器上使用,並且可以使用相同的類名稱但不同的css屬性來設置兩個div。因此,通過查看兩個div的屬性可以很容易地看到它們的表現。而使用nth-child選擇器用戶必須爲每個選定元素定義css屬性。 – frnt

+0

是的。你可以使用'nnth-child'。但在同一時間你可以風格'。容器{背景:紅色;位置:絕對;寬度:50px}'等等,例如寫'.container:nth-​​child(2){background:blue;}'; '.container:nth-​​child(5){background:yellow;}'等等,只是改變那個特定於那個'nth-child'的樣式。 –

0

你只需要給Z-index屬性吧。 z-index屬性指定元素的堆棧順序。堆棧順序較大的元素始終位於堆棧順序較低的元素前面。注:z-index僅適用於定位元素(位置:絕對,位置:相對或位置:固定)。

.inner { 
    top: 5px; 
    left: -10px; 
    right: -50px; 
    bottom: -10px; 
    background-color: green; 
    position: absolute; 
    z-index:1; 
} 

你可以看到演示here

+0

第一個紅色框(在左邊;內部的父項)必須位於綠色框(內部)的頂部, –