Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS z-index not working (position absolute) [duplicate]

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:

enter image description here

like image 612
HTMHell Avatar asked Jan 07 '14 12:01

HTMHell


People also ask

Can I use Z index with position absolute?

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

Why is Z Index not working CSS?

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.

How do I fix Z index in CSS?

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.

How do you use Z index without absolute positioning?

Yes: use position:relative; z-index:10 . z-index has no effect for position:static (the default).


2 Answers

Remove

z-index:0; 

from .absolute.

Updated fiddle here.

like image 55
codingrose Avatar answered Sep 29 '22 11:09

codingrose


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/

like image 44
xec Avatar answered Sep 29 '22 09:09

xec