I am trying to make the black div
(relative) above the second yellow one (absolute). The black div
's parent has a position absolute, too.
#relative { position: relative; width: 40px; height: 100px; background: #000; z-index: 1; margin-top: 30px; } .absolute { position: absolute; top: 0; left: 0; width: 200px; height: 50px; background: yellow; z-index: 0; }
<div class="absolute"> <div id="relative"></div> </div> <div class="absolute" style="top: 54px"></div>
Expected Result:
Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).
z-index only works on positioned elements (relative, absolute, fixed, sticky) so if you set a z-index on an element with a static position, it won't work.
The solution to this is to set position: relative and explicitly set z-index on at least the white block. You could go one step further and set position: relative and a lower z-index on the cat elements, just to be extra safe. In my opinion, doing this will solve most, if not all of the more basic z-index issues.
Yes: use position:relative; z-index:10 . z-index has no effect for position:static (the default).
Remove
z-index:0;
from .absolute
.
Updated fiddle here.
This is because of the Stacking Context, setting a z-index will make it apply to all children as well.
You could make the two <div>
s siblings instead of descendants.
<div class="absolute"></div> <div id="relative"></div>
http://jsfiddle.net/P7c9q/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With