简体   繁体   English

CSS Z-index无法与相对定位一起使用

[英]CSS z-index not working with relative positioning

I have some divs like so: 我有一些像这样的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>

I want #one (stacked over) #two (stacked over) #three but all I get is #one (before) #two (before) #three just as they would appear without applying and any z-index. 我想要#one (stacked over) #two (stacked over) #three但我得到的只是#one (before) #two (before) #three ,就像它们没有应用和出现任何z-index一样。 How can I make my z-indices work, and more importantly why is my code not working? 如何使我的z索引起作用,更重要的是为什么我的代码不起作用?

You have to use top and left attributes. 您必须使用topleft属性。 Look at this solution https://jsfiddle.net/f5L4puaa/ 看看这个解决方案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>

Here's a working example using "absolute" positioning: https://jsfiddle.net/x32m5rhv/1 这是一个使用“绝对”定位的工作示例: https : //jsfiddle.net/x32m5rhv/1

 <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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM