Vijay Singh
Vijay Singh

Reputation: 277

CSS z-index not working with relative positioning

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?

Upvotes: 1

Views: 2428

Answers (2)

Kirill Chatrov
Kirill Chatrov

Reputation: 832

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>

Upvotes: 0

misabelcarde
misabelcarde

Reputation: 83

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>

Upvotes: 1

Related Questions