CSS z-index not working with relative positioning

二次信任 提交于 2019-12-11 13:04:53

问题


I have some divs like so:

<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. How can I make my z-indices work, and more importantly why is my code not working?


回答1:


You have to use top and left attributes. Look at this solution 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>



回答2:


Here's a working example using "absolute" positioning: 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>


来源:https://stackoverflow.com/questions/35611927/css-z-index-not-working-with-relative-positioning

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!