2016-11-25 45 views
0

我試圖用透明覆蓋層覆蓋除了一個div以外的整個頁面。問題是,我想要頂部的div是fixed div的孩子。我如何將它放在頂層,但將其父層放在覆蓋層下面?在內部div上應用z-index以在覆蓋層上出現

在下面的代碼中,我想要覆蓋層上的元素是.holder。這是JS Fiddle

HTML:

<!DOCTYPE html> 
<html> 
    <head> 
    <title>z-index tests</title> 
    <link rel="stylesheet" type="text/css" href="style.css"> 
    </head> 
    <body> 
    <div class="root"> 
    Root 
     <div class="header"> 
     Header 
     <div class="holder"> 
      Holder 
     </div> 
     </div> 
     <div class="content"> 
     content 
     <div class="box"></div> 
     </div> 
    </div> 
    <div class="overlay"></div> 
    </body> 
</html> 

CSS:

.box { 
    height: 100px; 
    width: 100px; 
    border: 1px solid #000; 
} 

.root { 
    display: block; 
    background-color: grey; 
} 

.header { 
    background-color: red; 
    position: fixed; 
    top: 0px; 
    width: 1600px; 
} 

.holder { 
    background-color: green; 
    height: 60px; 
    width: 1600px; 
    z-index: 1002; 
    position: absolute; 
} 

.content { 
    background-color: blue; 
} 

.overlay { 
    position: fixed; 
    top:0; 
    bottom:0; 
    left:0; 
    right:0; 
    background-color: rgb(50,50,50); 
    opacity:0.8; 
    z-index:10; 
} 

回答

1

你不能。這就是z-index和堆疊層的工作方式。直到.holder.header後裔它通過position: fixed創建它自己的堆疊環境,只有這樣,才能推動.holder上面覆蓋是它在DOM樹之外移動.header並使它的.overlay兄弟姐妹或後代。

第二個選項(但我猜.header不是沒有原因修復的)就是將.header的樣式更改爲不創建堆棧上下文,例如。將其位置更改爲absolute並刪除z-index。在這種情況下,.holder的堆疊上下文將與.overlay同等水平,您可以使用z-index操縱那些深度。

list of CSS properties創建新的堆疊上下文。

我知道我離開你傷心欲絕。

+0

還是要謝謝你Eryk。我要用一種不同的方法來做我想做的事情。 [這](http://stackoverflow.com/a/28616718/1840918)將爲我的目的工作,並可能爲我節省很多頭痛! – Abdul

1

你可以欺騙,並通過添加一個巨大的box-shadow到.holder達到同樣的效果:

.box { 
 
    height: 100px; 
 
    width: 100px; 
 
    border: 1px solid #000; 
 
} 
 

 
.root { 
 
    display: block; 
 
    background-color: grey; 
 
} 
 

 
.header { 
 
    background-color: red; 
 
    position: fixed; 
 
    top: 0px; 
 
    width: 1600px; 
 
    /*z-index: 1;*/ 
 
} 
 

 
.holder { 
 
    background-color: green; 
 
    height: 60px; 
 
    width: 1600px; 
 
    z-index: 1002; 
 
    position: absolute; 
 
} 
 

 
.content { 
 
    background-color: blue; 
 
} 
 

 
.highlight { 
 
    box-shadow:0 0 0 9999999px rgba(50,50,50,0.8); 
 
}
<div class="root"> 
 
    Root 
 
    <div class="header"> 
 
     Header 
 
     <div class="holder highlight"> 
 
     Holder 
 
     </div> 
 
    </div> 
 
    <div class="content"> 
 
     content 
 
     <div class="box"></div> 
 
    </div> 
 
    </div>

JS Fiddle