CSS z-index不适用于相对定位

时间:2016-02-24 20:02:18

标签: html css z-index

我有一些像这样的div:

<html>
<body>
<div id="out">
        <div id="in">
                <div id="one" style="position: relative; z-index: 3">
                </div>
                <div id="two" style="position: relative; z-index: 2">
                </div>
                <canvas id="three" style="position: relative; z-index: 1">
                </canvas>
                <canvas id="four" class="hidden">
                </canvas>
        </div>

        <-- Some more divs with position: static (default)-->


</div>
</body>
</html>

我想要#one (stacked over) #two (stacked over) #three,但我得到的只是#one (before) #two (before) #three,就像没有应用和任何z索引一样。如何使我的z-index工作,更重要的是为什么我的代码不起作用?

2 个答案:

答案 0 :(得分:1)

您必须使用topleft属性。看看这个解决方案https://jsfiddle.net/f5L4puaa/

<div id="out">
    <div id="in">
    <div id="one" style="position: relative; z-index: 3; background-color:orange; top: 3.5em;">div one
    </div>
    <div id="two" style="position: relative; z-index: 2;  background-color: yellow; top:3em;">div two
    </div>
    <canvas id="three" style="position: relative; z-index: 1;  background-color:pink;">div three
    </canvas>
    <canvas id="four" class="hidden">
    </canvas>
    </div>
</div>

答案 1 :(得分:0)

这是一个使用&#34;绝对&#34;的工作示例定位:https://jsfiddle.net/x32m5rhv/1

&#13;
&#13;
<div>
		<div id="myBox" style="border: 1px solid #000; width: 100px; height: 100px; z-index: 4; position: absolute; background-color: #ff0000; opacity:0.8">myBox z-index 4</div>
		<div style="width:100px;height:100px;position:absolute;background-color:yellow;top:20px;left:20px;z-index:0;opacity:0.5;border:1px solid #333333;">z-index 0</div>
		<div style="width:100px;height:100px;position:absolute;background-color:yellow;top:40px;left:40px;z-index:1;opacity:0.5;border:1px solid #333333;">z-index 1</div>
		<div style="width:100px;height:100px;position:absolute;background-color:yellow;top:60px;left:60px;z-index:2;opacity:0.5;border:1px solid #333333;">z-index 2</div>
		<div style="width:100px;height:100px;position:absolute;background-color:yellow;top:80px;left:80px;z-index:3;opacity:0.5;border:1px solid #333333;">z-index 3</div>
</div>
&#13;
&#13;
&#13;