Tutorial :What is the relation between z-index and css Position:?



Question:

What is the relation between z-index and css Position:?

Is z-index only works if position:absolute or relative or fixed defined?

Does it never works with position static?

When z-index creates problem in IE? How to use carefully?


Solution:1

z-index defines the stacking order of relative, absolute and fixed position elements. That means that it will only work if your element has one of those position types.

.some-element {      position: relative;      z-index: 1;  }    .another-element {      position: absolute;      z-index: 2;  }  

In the above, .another-element will stack above .some-element since it has a higher z-index.

The issue with older versions of IE is that z-index is only respected in the same stacking context. What this means is that in the following setup, z-index won't necessarily work correctly if the 2 images overlap:

HTML

<div id="elem1">      <img src="foo.jpg"/>  </div>   <div id="elem2">      <img src="bar.jpg"/>  </div>  

CSS

#elem1 {      position: relative;  }  #elem1 img {      position: relative;      z-index: 1;  }  #elem2 {      position: relative;  }  #elem2 img {      position: relative;      z-index: 2;  }  

The reason being that both images are in their own stacking context since #elem1 and #elem2 are position: relative.


Solution:2

Note the Applies to: section of the specification:

'z-index'     Value:     auto | <integer> | inherit     Initial:   auto     Applies to:    positioned elements   

â€"

And you can easily use the index to find the definition of positioned


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »