2014-02-26 41 views
2

我遇到了很大的麻煩,使我的頁面顯示正確定位和分層。在Chrome中使用固定位置的CSS z-index

這是更大的,但基本佈局是完全一樣的,因爲我創造了它在這裏: http://codepen.io/rjk/pen/AsGfm

頁眉和頁腳是固定的,當頁面內容是圍繞滾動不動。什麼是真正重要的是,其結構是:

<div id="login-container"> 
    <button id="login-panel-button">Login</button> 
    <div id="login-panel"> 
    <form id="login-form"> 
     ... 
    </form> 
    </div> 
</div> 

#加載頁面時登錄面板是隱藏的。唯一的方法是點擊#登錄面板按鈕,除此之外,它還模糊了一切(除了#登錄面板按鈕)。我通過顯示/隱藏透明黑色背景的全屏圖像來模糊圖像#background-blur。問題來了。

我想模糊了一切,但不是#登錄面板#登錄面板的按鈕。因此,我已分配z索引:1#背景模糊的z-index:2#登錄容器。花了一段時間才明白,爲什麼它不起作用。其原因是,Chrome爲每個具有排名的元素創建一個新的堆疊上下文:固定的z-index分層是相對的,這意味着指定的z-索引值僅適用於它的堆棧上下文(最接近於自己創建堆棧上下文的祖先或根元素)。只有在頭的方面,它有它的默認的z-index我#登錄面板的3:所以我指定的z-index 0(它就像是ž#登錄面板 -index:0.1),並顯示在#background-blurz-index:1

當然,我可能只是提高頭的z-index的到,但不是當我想#logo被模糊(下方顯示#背景模糊)。然後我可以分別創建#logo#登錄面板單獨創建單獨的堆棧上下文位置:固定,但我失去了將它們放置在800px居中容器中的能力(在兩側)我需要。

該問題僅與Chrome相關。嘗試運行我在Firefox中提供的筆,一切都像魅力一樣。

對於任何人想要一個良好的閱讀,MDN有一個很好的徹底文章(與堆疊內容第4節): https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Understanding_z_index

+2

詳情前提是你不錯,但你應該考慮砍他們的時間,來點......用戶將無法讀取的解釋,即大塊:) –

+0

如果登錄容器是位置固定的,爲什麼不把它放在body中而不是在header中 – Pete

+0

pete,#login-container有位置相對。 –

回答

1

如果身體內移動的登錄容器到它自己固定的位置容器,你可以給它相同的尺寸爲您的頭和它自己的z-index,所以你就可以達到你想要的東西:

HTML

<body> 
    <div class="center"> 
    <div id="login-container"> 
     <button id="login-panel-button">Login</button> 
     <div id="login-panel"> 
     <form id="login-form"> 
      <label for="username">Username:</label> 
      <input type="text" name="username" id="username"></input> 
      <label for="username">Password:</label> 
      <input type="password" name="password" id="password"></input> 
     </form> 
     </div> 
    </div> 
    </div> 
<header> 
    etc... 

CSS

header, 
footer, 
.center { 
    width: 800px; 
    left: 0; 
    right: 0; 
    margin-left: auto; 
    margin-right: auto; 
} 

header, 
.center { 
    position: fixed; 
    top: 10px; 
} 

.center { 
    z-index:2; 
} 

Updated Codepen