Css3 why z-index does not work with position relative?

Code below works fine. But changing position to relative destroys the overlapping effect. Why?

It seems it has something to do with position:relative creating a new containing block for every element it is applied on, but i am only speculating

<body>
	<div style="position:absolute; left:0px; top: 0px; z-index: 1;">111111</div>		
	<div style="position:absolute; left:0px; top: 0px; z-index: 2;">222222222</div>
</body>

Thanks

Because it then refer its coordinates to its own place, as absolute positioned it referred to the html root. Try play with the coordinates and see.

I think you have put exacly this question before and got a full explanation already?.

i posted it on stackoverflow. and all i got was a bunch of nazis kicking my ass for asking. i hate that.

Sorry, the thorough explanation I had in memory was posted here in this forum some months ago but apparently not in a thread by you. Sad to hear you were met with insults, that isn’t the SO I know, I hope you flagged their posts.

Did my answer clarify why the div behaved differently given a relative position instead of the absolute?

3 Likes

If you change both to relative then as the co-ordinates are zero that means the elements have not been moved at all and will just occupy space in the logical normal flow of the document one after the other and will not overlap.

If you change only one element to relative then the elements may or may not overlap but it will depend where the closest positioned ancestor lies (either relative or absolute). If none exists then the absolute co-ordinates are taken from the root element which may or may not be where your relative element is resisiding and thus will depend whether they overlap or not. Generally the root element (html) has margin/padding applied by default so if you only have two elements on the page then the relative element will not be flush to the viewport edge but the absolute element will.

You can read more about relative positioning in the following thread.

4 Likes

thanks Eirk. i think ypur explanation shed some light. some link you want to recommend? thank you

thank you paul. will read it. cheers

Read the whole of this thread: dCode_Understanding CSS Positioning by @PaulOB (he already cited from it)

For the z-index you can find it all out here: https://www.w3.org/TR/CSS21/visuren.html#propdef-z-index

Maybe the most convenient is to check http://reference.sitepoint.com/css

thanks man. happy holidays.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.