tags:

views:

58

answers:

2

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?

+2  A: 

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

David Dorward
I appreciate the references (+1), but why not also state the answer plainly?
Patrick McElhaney
@Patrick McElhaney - Agree with you. I was also expecting in plain. W3C links content is very long.
metal-gear-solid
+2  A: 

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.

Pat
Suggestion: Inline the styles so one doesn't need to jump back and forth between the HTML and CSS.
Patrick McElhaney
@pat - so z-index doesn't care about positioning. element with higher z-index will be always on top. Am i right?
metal-gear-solid
@metal-gear-solid: Yep, z-index isn't affected by the type of position, but it will only work if one of the 3 position types is specified on the element. And see the bit in my answer about stacking contexts to see where this isn't always true in IE.
Pat
@Pat - Is "stacking level" same thing like layers in photoshop?
metal-gear-solid
@metal-gear-solid: yes, that's a good analogy.
Pat
@pat - are IE6 and 7 only browsers which has `z-index` problem?
metal-gear-solid
@pat- i created one z-index example here http://jsbin.com/uxihu3. with the help of this can you explain the problem of z-index in IE?
metal-gear-solid
@metal-gear-solid: I'm not 100% positive, but they're the only two I've ever had problems with. A workaround if you run into the problem is to apply z-index to the elements that have created the stacking contexts (i.e. in my example, you could add z-index to #elem1 and #elem2 to fix the problem).
Pat