Jitendra Vyas
Jitendra Vyas

Reputation: 152945

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

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?

Upvotes: 3

Views: 842

Answers (2)

Pat
Pat

Reputation: 25685

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.

Upvotes: 3

Quentin
Quentin

Reputation: 944538

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

Upvotes: 2

Related Questions