2014-01-07 90 views
37

我想讓第二個黃色(絕對)以上的黑色div(相對)。黑div的父母也有一個絕對的位置。CSS z-index不工作(絕對位置)

代碼:

<div class="absolute"> 
    <div id="relative"></div> 
</div> 
<div class="absolute" style="top: 54px"></div> 
<style> 
#relative { 
    position: relative; 
    width: 40px; 
    height: 100px; 
    background: #000; 
    z-index: 1; 
    margin-top: 30px; 
} 
.absolute { 
    position: absolute; 
    top: 0; left: 0; 
    width: 200px; 
    height: 50px; 
    background: yellow; 
    z-index: 0; 
} 
</style> 

的jsfiddle:http://jsfiddle.net/P7c9q/

回答

1

其他。第二格之前只需添加第二.absolute DIV:

<div class="absolute" style="top: 54px"></div> 
<div class="absolute"> 
    <div id="relative"></div> 
</div> 

因爲這兩個元件具有索引0。

0

JSFiddle

你必須把第二個div上的第一個頂部,因爲兩者具有零的z-index,這樣在DOM的順序將決定其在頂部。這也會影響相對定位div,因爲它的z-index與父div內的元素有關。

<div class="absolute" style="top: 54px"></div> 
<div class="absolute"> 
    <div id="relative"></div> 
</div> 

Css保持不變。

0

這個怎麼樣?

http://jsfiddle.net/P7c9q/4/

<div class="relative"> 
    <div class="yellow-div"></div> 
    <div class="yellow-div"></div> 
    <div class="absolute"></div> 
</div> 

.relative{ 
position:relative; 
} 

.absolute { 
position:absolute; 
width: 40px; 
height: 100px; 
background: #000; 
z-index: 1; 
top:30px; 
left:0px; 
} 
.yellow-div { 
position:relative; 
width: 200px; 
height: 50px; 
background: yellow; 
margin-bottom:4px; 
z-index:0; 
} 

使用相對DIV的包裝,讓黃div的有正常的定位。

只有黑塊需要有絕對位置。

2

我努力弄明白如何把一個div在這樣的圖像: z-index working

不管我怎麼在這兩種申報單(圖像包裝)配置的z-index和部分我得到這樣的:

z-index Not working

原來我還沒有成立的部分的背景是background: white;

所以基本上它像這樣的:

<div class="img-wrp"> 
    <img src="myimage.svg"/> 
</div> 
<section> 
<other content> 
</section> 

section{ 
    position: relative; 
    background: white; /* THIS IS THE IMPORTANT PART NOT TO FORGET */ 
} 
.img-wrp{ 
    position: absolute; 
    z-index: -1; /* also worked with 0 but just to be sure */ 
} 
2

我被這個問題所困擾,我學到(感謝this後)認爲:

透明度也會影響z-index的

div:first-child { 
 
    opacity: .99; 
 
} 
 

 
.red, .green, .blue { 
 
    position: absolute; 
 
    width: 100px; 
 
    color: white; 
 
    line-height: 100px; 
 
    text-align: center; 
 
} 
 

 
.red { 
 
    z-index: 1; 
 
    top: 20px; 
 
    left: 20px; 
 
    background: red; 
 
} 
 

 
.green { 
 
    top: 60px; 
 
    left: 60px; 
 
    background: green; 
 
} 
 

 
.blue { 
 
    top: 100px; 
 
    left: 100px; 
 
    background: blue; 
 
}
<div> 
 
    <span class="red">Red</span> 
 
</div> 
 
<div> 
 
    <span class="green">Green</span> 
 
</div> 
 
<div> 
 
    <span class="blue">Blue</span> 
 
</div>

+1

[在Mozzila開發者頁面上](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context),你可以找到更多的細節堆疊。 – Darkowic