2014-01-07 92 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