使用z-index定位DIV

时间:2012-12-04 21:45:34

标签: html css css3 z-index

我目前正在尝试使用z-index按特定顺序定位某些DIV,但它们似乎没有动摇我已经在jsfiddle中设置它让你看看是否可以看到任何问题

这是我希望它从后到前的顺序:

RED 绿色 蓝色 YELLOW

http://jsfiddle.net/BUWaZ/4/

HTML

<div id="green">

   <div id="yellow">
   </div>

   <div id="red">
   </div>

</div>

<div id="blue">
</div>

CSS

#green{
   background-color:green;
   height:100px;
   width:100%;
   position:fixed;
   top:0;
}

#red {
   margin:-85px auto 0;
   width:406px;
   height:60px;
   background-color:red;
z-index:-99999;   
}

#blue{
   margin:350px auto 0;
   width:60px;
   height:465px;
   z-index:99999;
   background-color:blue;
}

#yellow {
   margin:0px auto 0;
   width:170px;
   height:170px;
   background-color:yellow;
   z-index:99999;   
}

2 个答案:

答案 0 :(得分:3)

您必须设置一个位置才能使z-index工作。添加相对于没有它的位置。对蓝色和黄色也没有相同的z-index,或者不知道选择哪一个。

http://jsfiddle.net/SzxT2/1/

#green{
    background-color:green;
    height:100px;
    width:100%;
    position:fixed;
    top:0;
}

#red {
    margin:-85px auto 0;
    width:406px;
    height:60px;
    background-color:red;
z-index:-99999;    
    position:relative;
}

#blue{
    margin:350px auto 0;
    width:60px;
    height:465px;
    z-index:99998;
    background-color:blue;
    position:relative;
}

#yellow {
    margin:0px auto 0;
    width:170px;
    height:170px;
    background-color:yellow;
    z-index:99999;   
    position:relative;
}

答案 1 :(得分:0)

除了必须为z-index'ed元素定义位置之外,您无法为将要将其置于其父级之后的子元素定义z-index。 (also see

查看以下内容是否适用于您: jsfiddle.net/BUWaZ/7/

HTML

<div id="green">
</div>

<div id="yellow_placer">
    <div id="yellow">
    </div>
</div>

<div id="red_placer">
    <div id="red">
    </div>
</div>

<div id="blue">
</div>​

CSS

#red {
   margin:0 auto 0;
   width:406px;
   height:60px;
   background-color:red;
   position:relative;
   z-index:100;   
}
#red_placer {
   width:100%;
   position:fixed;
   top:85px;
   z-index:100; 
}

#green{
   background-color:green;
   height:100px;
   width:100%;
   top:0;
   position:fixed;
   z-index:200; 
}

#blue{
   margin:30px auto 0;
   width:60px;
   height:465px;
   background-color:blue;
   position:relative;
   z-index:300;
}

#yellow {
   margin:0px auto 0;
   width:170px;
   height:170px;
   background-color:yellow;
   position:relative;
   z-index:400;   
}
#yellow_placer {
   width:100%;
   position:fixed;
   top:0;
   z-index:400; 
}​