2016-09-24 76 views
0

我有兩個DIV元素在同一水平上:bar and nav::before僞元素。僞元素:正確的z-index堆棧上下文?

|- nav text 
    |- nav pseudo element 
     |- bar 

*, 
 
*::after, 
 
*::before { 
 
    box-sizing: border-box; 
 
    margin: 0; 
 
} 
 
header { 
 
    position: relative; 
 
} 
 
.bar { 
 
    color: white; 
 
    background-color: black; 
 
} 
 
.nav { 
 
    background-color: orange; 
 
} 
 
p { 
 
    color: white; 
 
    margin-left: 10%; 
 
} 
 
.nav::before { 
 
    z-index: 0; 
 
    content: ""; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    right: 40%; 
 
    bottom: 0; 
 
    height: 0; 
 
    border-style: solid; 
 
    border-width: 4rem 4rem 0 0; 
 
    border-color: green transparent transparent transparent; 
 
}
<header> 
 
    <div class="bar">bar that should remain under green</div> 
 
    <div class="nav"> 
 
    <p>text that should appear above green</p> 
 
    </div> 
 
</header>

回答

0

只需添加:

導航酒吧應在導航它上面,像這樣下::before僞元素,但文字顯示相同的屬性文本。

*, 
 
*::after, 
 
*::before { 
 
    box-sizing: border-box; 
 
    margin: 0; 
 
} 
 
header { 
 
    position: relative; 
 
} 
 
.bar { 
 
    color: white; 
 
    background-color: black; 
 
} 
 
.nav { 
 
    background-color: orange; 
 
} 
 
p { 
 
    color: white; 
 
    margin-left: 10%; 
 
    z-index: 1; 
 
    position: relative; 
 
} 
 
.nav::before { 
 
    z-index: 0; 
 
    content: ""; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    right: 40%; 
 
    bottom: 0; 
 
    height: 0; 
 
    border-style: solid; 
 
    border-width: 4rem 4rem 0 0; 
 
    border-color: green transparent transparent transparent; 
 
}
<header> 
 
    <div class="bar">bar that should remain under green</div> 
 
    <div class="nav"> 
 
    <p>text that should appear above green</p> 
 
    </div> 
 
</header>

+0

它的工作原理!爲什麼'position:relative'在這裏很重要? –

+0

如果尚未設置任何位置規則,則不能設置z-index。發生這種情況是因爲所有元素的自然位置都與其他元素不重疊,因此在選擇默認非重疊位置時不需要z-index。 –