2011-02-28 59 views
1

我的代碼如下所示:使用z-index在其他元素前面創建一個嵌套元素?

css: 

.top { 
position: absolute; 
top:0; 
left:0; 
height: 1600px; 
width: 100%; 
z-index: -100; 

} 

.bar { 
position: relative; 
z-index: -200; 
width: 100% 
height: 100px; 

} 

.inner-bar { 
position: relative; 
z-index: 100; 
width: 100% 
height: 50px; 

} 



html: 

<body> 
<div class="top">some content</div> 

<div class="bar"> 
    <div class="inner-bar">some content</div> 
<div> 

</body> 

正如你可以看到,我試圖讓內酒吧出現在面前,但這不起作用。一旦我將酒吧設置在所有事物的後面(這是有效的),這也將內部酒吧設置在任何事物的後面,而不管我爲內部酒吧做什麼樣式。我的佈局要求內部酒吧必須是酒吧的孩子。那麼有沒有解決方案,它是什麼?

爲了說清楚我的目標是讓酒吧在頂部出現(頂部的內容出現在酒吧上)並讓內部酒吧背後(頂部的內容隱藏,如果它與內部酒吧重疊,以便內部的鏈接-bar是活動的)。

+0

你'的z-index:-200'爲' .bar'如何在'.top'前面有'z-index:-100'?如果理解正確,則必須刪除'.bar'的'z-index'並僅使用'.inner-bar'的'z-index'。 – Sotiris 2011-02-28 15:46:18

+0

你有沒有試過這個:http://stackoverflow.com/questions/361359/how-can-i-get-desired-z-index-behavior-from-ie-when-using-nested-divs – corroded 2011-02-28 15:47:08

+0

使用負面的' z-index'通常以* something *爲無法選擇或不可點擊結束。由於這種非常惱人的趨勢,最好謹慎使用。 – thirtydot 2011-02-28 15:50:04

回答

0

第一關有在您發佈的HTML錯誤:

<body> 
    <div class="top">some content</div> 
    <div class="bar"> 
     <div class="inner-bar">some content</div> 
    </div> 
</body> 

你沒有關閉最後一個div :)

爲其餘的:

在這裏你去好先生! http://jsfiddle.net/8AJnD/31/

.top { 
    position: absolute; 
    top:0; 
    left:0; 
    height: 1600px; 
    width: 100%; 
    top:0;left:0;z-index:0; 
} 

.bar { 
    position: absolute;z-index:-1; 
    width: 100%; 
    height: 100px;top:0;left:0 
} 

.inner-bar { 
    position: absolute; 
    z-index:-2; 
    width: 100% 
    height: 50px;top:0;left:0 
} 

使用絕對的,而不是相對的,相對於母公司的做出能夠要素位置。然而,你希望他們的那一刻起定位

+1

這並不能解決問題,'''.top'''已經超過'''.inner-bar'''。 – Korri 2013-06-20 19:18:38

+0

@Korri,不在我的jsfiddle:s – cmplieger 2013-06-21 02:07:03

+0

是在你的jsfiddle中,在Chrome和Firefox下試用它們,並且都在頂部顯示紅色/黃色文本('''.top''')。 – Korri 2013-07-12 03:32:40

0

負Z指標值有奇怪的行爲。我不認爲他們像你所期望的那樣在「層」上工作,而是他們都在同一個「層」上。嘗試使用積極的z-index值而不是:

.top { 
    position: absolute; 
    top:0; 
    left:0; 
    height: 1600px; 
    width: 100%; 
    z-index: 1;  
} 

.bar { 
    position: relative; 
    z-index: 2; 
    width: 100% 
    height: 100px; 
} 

.inner-bar { 
    position: relative; 
    z-index: 3; 
    width: 100% 
    height: 50px; 
} 
+0

感謝您的提示,但不幸的是,這不起作用,並使其更糟,因爲(我認爲)其他元素的默認z-index爲零。在這種情況下,所有其他元素(包括那些靜態定位的元素)中的所有鏈接都變得無法點擊,因爲頂層現在位於頂層。 – ace 2011-02-28 16:38:00